Telegram Python Bot | Event when Bot is added to a group - python

i am developing a python script for my telegram right now. The problem is:
How do I know when my bot is added to a group? Is there an Event or something else for that?
I want the Bot to send a message to the group he´s beeing added to which says hi and the functions he can.
I dont know if any kind of handler is able deal with this.

Very roughly, you would need to do something like this: register an handler that filters only service messages about new chat members. Then check if the bot is one of the new chat members.
from telegram.ext import Updater, MessageHandler, Filters
def new_member(bot, update):
for member in update.message.new_chat_members:
if member.username == 'YourBot':
update.message.reply_text('Welcome')
updater = Updater('TOKEN')
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))
updater.start_polling()
updater.idle()

With callbacks (preferred)
As of version 12, the preferred way to handle updates is via callbacks. To use them prior to version 13 state use_context=True in your Updater. Version 13 will have this as default.
from telegram.ext import Updater, MessageHandler, Filters
def new_member(update, context):
for member in update.message.new_chat_members:
if member.username == 'YourBot':
update.message.reply_text('Welcome')
updater = Updater('TOKEN', use_context=True) # use_context will be True by default in version 13+
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))
updater.start_polling()
updater.idle()
Please note that the order changed here. Instead of having the update as second, it is now the first argument. Executing the code below will result in an Exception like this:
AttributeError: 'CallbackContext' object has no attribute 'message'
Without callbacks (deprecated in version 12)
Blatantly copying from mcont's answer:
from telegram.ext import Updater, MessageHandler, Filters
def new_member(bot, update):
for member in update.message.new_chat_members:
if member.username == 'YourBot':
update.message.reply_text('Welcome')
updater = Updater('TOKEN')
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, new_member))
updater.start_polling()
updater.idle()

Related

I got error AttributeError: 'Updater' object has no attribute 'dispatcher'

I got error when running python script to integrate openai with telegram bot. here is my code:
# Import the necessary modules
import telegram
import openai
from telegram.ext import CommandHandler, MessageHandler, Updater
from queue import Queue
# Initialize the Telegram bot
bot = telegram.Bot(token='')
# Initialize the OpenAI API
openai.api_key = ''
# Define a function to handle /start command
def start(bot, update):
bot.send_message(chat_id=update.message.chat_id, text="Hi! I'm a ChatGPT bot. Send me a message and I'll try to respond to it.")
# Define a function to handle messages
def message(bot, update):
# Get the message text
message_text = update.message.text
# Call the OpenAI API to generate a response
response = openai.Completion.create(
engine="davinci",
prompt=message_text,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
# Get the response text from the API
response_text = response.choices[0].text.strip()
# Send the response back to the user
bot.send_message(chat_id=update.message.chat_id, text=response_text)
# Initialize the Telegram bot updater and dispatcher
update_queue = Queue()
updater = Updater(bot=bot, update_queue=update_queue)
dispatcher = updater.dispatcher
# Add command handlers
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
# Add message handler
message_handler = MessageHandler(None, message)
dispatcher.add_handler(message_handler)
# Start the Telegram bot
updater.start_polling()
The error :
dispatcher = updater.dispatcher
^^^^^^^^^^^^^^^^^^
AttributeError: 'Updater' object has no attribute 'dispatcher'
I don't know how to fix this, because I've already see many solution but it tell me to update telegram-bot.
is there any solution to this? I've already upgrade telegram-bot but still error.
I think 'dispatcher' is no longer used in version 20.0a0
If you want to use your code then you can downgrade as:
pip install python-telegram-bot==13.3
If you are using v20 then you have to build your application differently and you have to use async functions.

Telegram Bot Check If Member In Group Is Deleted

I'm trying to code a telegram bot to remove any deleted accounts in the group chat but with telegram removing get_chat_members in later versions I'm at a lost, here's my current code how can I get all the members or loop through all members to check rather the account is deleted or not?
from telegram import *
from telegram.ext import *
from requests import *
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.ext import CallbackQueryHandler, CallbackContext
from telegram.ext.dispatcher import run_async
from telegram.ext.jobqueue import Days
# Create a new Telegram bot & # Start the bot and connect to the Telegram API
updater = Updater(token="bot_token", use_context=True)
dispatcher = updater.dispatcher
# Define a command handler for the /start command, which prints a greeting
def start(update: Update, context: CallbackContext):
context.bot.send_message(chat_id=update.effective_chat.id, text="Hello! I am RDA_bot, a bot that removes deleted accounts from a Telegram group.")
# Define a command handler for the /remove command, which removes deleted accounts from the group
def remove(update: Update, context: CallbackContext):
# Get a list of all members of the group
members = #NEED HELP HERE
# Count how many members have deleted their account
deleted_accounts = 0
for member in members:
if member.user.is_deleted:
deleted_accounts += 1
# Send a message to the user with the number of deleted accounts
context.bot.send_message(chat_id=update.effective_chat.id, text=f"Removed {deleted_accounts} deleted accounts from the group.")
# Define a command handler for the /remove command, which removes deleted accounts from the group
def remove(update: Update, context: CallbackContext):
# Get a list of all members of the group
members = #NEED HELP HERE
# Loop through each member of the group
for member in members:
# If the member's account has been deleted, kick them from the group
if member.user.is_deleted: #NEED TO CHECK IF THE USER IS DELETED
context.bot.kick_chat_member(chat_id=update.effective_chat.id, user_id=member.user.id, until_date=0)
# Create a job that runs every 24 hours to remove deleted accounts from the group
job_queue = updater.job_queue
job = job_queue.run_repeating(remove, interval=Days(1), first=0)
# Add the command handlers to the dispatcher
start_handler = CommandHandler("start", start)
dispatcher.add_handler(start_handler)
remove_handler = CommandHandler("remove", remove)
dispatcher.add_handler(remove_handler)
# Start the bot
updater.start_polling()
tried get_chat_members(chat_id) but that's no longer available.
The Bot API does not contain functionality to retrieve the full member list of a chat. I'm also not aware of any reliable way of checking if an account has been deleted. Maybe getChat returns a helpful error message in that case, but I haven't tried that so far.

Unresolved attribute reference 'dispatcher' for class 'Updater'

I try to create a Telegram bot but I can't use property Update class.
import logging
from multiprocessing import Queue
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
def main():
update_queue = Queue()
updater = Updater("API KEY", use_context=True, update_queue=update_queue)
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
Idle say that there is no dispatcher in Update class. Try update Telegram api, didn't help. Can't find another way to update bot
Since version 20.0 the Updater is only used to fetch updates, from the docs:
Changed in version 20.0:
Removed argument and attribute user_sig_handler
The only arguments and attributes are now bot and update_queue as now the sole purpose of this class is to fetch updates. The entry point to a PTB application is now telegram.ext.Application.
So if you want to add a handler, use an Application.
An example, taken from the echo bot example:
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
"""Echo the user message."""
await update.message.reply_text(update.message.text)
def main() -> None:
"""Start the bot."""
# Create the Application and pass it your bot's token.
application = Application.builder().token("TOKEN").build()
# on different commands - answer in Telegram
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
# on non command i.e message - echo the message on Telegram
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
# Run the bot until the user presses Ctrl-C
application.run_polling()
if __name__ == "__main__":
main()

How to track the event of adding and removing a bot to the channel?

I have a Telegram Bot on aiogram, and I want to be notified when my bot is added or removed from channels.
But my code only works on groups.
What needs to be done to work on channels as well?
And here is the code:
import logging
from aiogram import Bot, Dispatcher, executor, types
from config import API_TOKEN
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(content_types=[types.ContentType.NEW_CHAT_MEMBERS, types.ContentType.LEFT_CHAT_MEMBER])
async def check_channel(message: types.Message):
print(message)
if __name__ == "__main__":
executor.start_polling(dp, skip_updates=True)
Use my_chat_member_handler instead.
More info: https://core.telegram.org/bots/api-changelog#march-9-2021
Added two new update types
Added updates about member status changes in chats, represented by the
class ChatMemberUpdated and the fields my_chat_member and chat_member
in the Update class. The bot must be an administrator in the chat to
receive chat_member updates about other chat members. By default, only
my_chat_member updates about the bot itself are received.

How to stop Telegram bot executing old code

I made my first simple telegram bot with python-telegram-bot. Here's the code:
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
token = '1234567890'
updater = Updater(token=token, use_context=True)
dispatcher = updater.dispatcher
def start(update, context):
context.bot.send_message(chat_id = update.effective_chat.id, text=f"hey,{update.effective_chat.username}!")
def unknown(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, didn't understand")
unknown_handler = MessageHandler(Filters.command, unknown)
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
dispatcher.add_handler(unknown_handler)
updater.start_polling()
I kept changing the message text in the code and then executing it, checking what happens in the bot. What I ended up is every time I do start, the bot sends any of the old message versions together with new one. I revoked the token and it helped.
My question is what happens under the hood and why the latest version of the code doesn't replace the old ones? Also, how can I deal with it without having to revoke token every time?

Categories