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?
Related
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.
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.
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()
I'm programming a Telegram bot in python using the library python-telegram-bot, but I have a problem: I need to get the username of the user (sorry for the pun), but I don't know how to do it in the main function. I have already searched on the internet, and everyone get the username in a function, using update.message.from_user.username. But I need to do it in the main function, because I want to send this username and some text to another Telegram user. Can you help me?
My current code is this:
import telegram
import logging
from telegram.ext import CommandHandler, CallbackQueryHandler, Updater
from functions import start, button
bot = telegram.Bot(token='')
updater = Updater(token='')
dispatcher = updater.dispatcher
logging.basicConfig(format='%(asctime)s - %(name)s'
' - %(levelname)s - %(message)s', level=logging.INFO)
start_handler = CommandHandler('start', start)
dispatcher.add_handler(start_handler)
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.start_polling()
updater.idle()
updater.stop()
See if this is what you're looking for:
def start (update, context):
#this will retrieve the user's username, as you already know
user = update.message.from_user
#this will send the information to some Telegram user
context.bot.send_message(chat_id = some_user_chat_id,
text = f'User {user} just hit start command!')
Once the user hit /start command, his/her username will be sent to the chat_id of your choice.
You can set middleware which handle new update from user and get username throw ctx.from.username
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()