Reputation: 581
I'm trying to send a message using Python-Telegram-Bot without waiting for a user response but can't get it to work and I get no errors.
Code:
def echo(context):
context.bot.send_message(chat_id=-516017547, text='test')
#chat_id is the group id I found by going to:
#https://api.telegram.org/bot<MY_API>/getUpdates
def main():
updater = Updater(API)
dp = updater.dispatcher
echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dp.add_handler(echo_handler)
updater.start_polling()
updater.idle()
main()
Upvotes: 3
Views: 9952
Reputation: 7060
In python-telegram-bot
, the handlers are there to handle incoming updates - and nothing else. However, to call a bot method, you just need an instance of telegram.Bot
. In your echo
function, that's available as context.bot
. However, it's also available in main
as updater.bot
or updater.dispatcher.bot
. Note that you can also use a bot instance without Updater
at all:
from telegram import Bot
bot = Bot(TOKEN)
bot.send_message(...)
PS: if you want to use echo
as callback for MessageHandler
, it must accept exactly to arguments update
and context
.
Update: This reply was written for PTB <= v13.x. Since v20.0, PTB is based on the asyncio
framework, which make the above snippet invalid. Please have a look at PTBs wiki for an introduction on how this works now.
Disclaimer: I'm currently the maintainer of python-telegram-bot
.
Upvotes: 8