I am trying to send messages to bot daily without trigger from user side (eg commandhadler) from second conversation onwards.
I have build a basic menu for bot to interact with user
But i am also trying to send messages daily through job_queue
I have refered codes which are using commandhandlers
dp.add_handler(CommandHandler("set", set_timer,
pass_args=True,
pass_job_queue=True,
pass_chat_data=True))
This is being set after user types /set .
But I am trying to find a way to automatically send messages every 30 seconds or set a fixed time for message to be sent daily
My code
from telegram.ext import Updater,CommandHandler
from telegram.ext import MessageHandler,Filters,InlineQueryHandler
import logging
import telegram
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger()
def start(bot, update):
update.message.reply_text("Hello , Thanks for choosing us!!")
def callback_minute(context: telegram.ext.CallbackContext):
chat_id = ?
context.bot.send_message(chat_id=chat_id,
text='Hi User, Add Fund to your account to start trading')
def main():
updater = Updater(token,use_context=True)
dp = updater.dispatcher
j = updater.job_queue
dp.add_handler(CommandHandler("start",start))
job_minute = j.run_repeating(callback_minute, interval=10, first=0)
updater.start_polling()
updater.idle()
How to get chat_id?
If i am using
def callback_minute(update, context: telegram.ext.CallbackContext):
chat_id = update.message.chat.id
I am getting this error
TypeError: callback_minute() missing 1 required positional argument: 'context'
2
Answers
You have to use
context.job_queue.run_repeating()
to repeat the job continuously after specific time interval.If you want the job to execute once everyday, you can use
context.job_queue.run_daily()
and specify the time.These are
python-telegram-bot
docs links for both of the cases:job_queue.run_repeating(), job_queue.run_daily()
These docs have very good information which will help your query.
It is reworked below so that run_repeating() is called from the
/start
command (as suggested by Gagan T K in the comments). In this examplefirst=30
so it will start after 30 seconds.There is a good example of using the job queue in this way at the bottom of the wiki documentation for JobQueue on GitHub.