Aaron Lee
Aaron Lee

Reputation: 11

Deploying telegram bot to production along with Django web-site

Here are my bot.py scripts:

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    update.message.reply_text("Start")


def main():
   updater = Updater(TOKEN, use_context=True)
   dp = updater.dispatcher

   dp.add_handler(CommandHandler("start", start))

   updater.start_polling()

   updater.idle()


if __name__ == '__main__':
    main()

I can run it locally by python bot.py However, I do not know how to deploy to the Django production server.

How to make it work with view.py? Do I have to create a view for it? Can anyone help?

Upvotes: 1

Views: 839

Answers (2)

wowkin2
wowkin2

Reputation: 6355

You need to create and store somewhere Dispatcher (have it like a Singleton) and serialize Update manually without using built-in Updater. See example with no threading.


from telegram import Bot, Update
from telegram.ext import Dispatcher

def create_dispatcher(token):
    # Create bot, update queue and dispatcher instances
    bot = Bot(token)
    
    dispatcher = Dispatcher(bot, None, workers=0)
    
    ##### Register handlers here #####
    
    return dispatcher


dispatcher = create_dispatcher(TOKEN_HERE)


def webhook_view(request)
    update = Update.de_json(json.loads(request.body.decode()), dispatcher.bot)
    dispatcher.process_update(update)
    return '{"status": "ok"}', 200

Also you'll need to setup Webhooks for that

Upvotes: 2

Thatcher Thornberry
Thatcher Thornberry

Reputation: 604

One possibility is to include it as a management command and run that command on a schedule (Heroku scheduler is easy if you want to deploy to Heroku https://devcenter.heroku.com/articles/scheduler). Management commands basically execute a function you define with the command python manage.py your_command_name. How to write custom management command https://docs.djangoproject.com/en/3.1/howto/custom-management-commands/

Upvotes: 0

Related Questions