-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot.py
55 lines (43 loc) · 1.91 KB
/
bot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import logging
import os
import random
import sys
from telegram import Update
from telegram.ext import Updater, CommandHandler, CallbackContext
# Enabling logging
logging.basicConfig(level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.getLogger()
# Getting mode, so we could define run function for local and Heroku setup
MODE = os.getenv("MODE")
TOKEN = os.getenv("TOKEN")
if MODE == "docker" or MODE == "dev":
def run(updater):
updater.start_polling()
elif MODE == "prod":
def run(updater):
PORT = int(os.environ.get("PORT", "8443"))
HEROKU_APP_NAME = os.environ.get("HEROKU_APP_NAME")
# Code from https://github.com/python-telegram-bot/python-telegram-bot/wiki/Webhooks#heroku
updater.start_webhook(listen="0.0.0.0",
port=PORT,
url_path=TOKEN)
updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(HEROKU_APP_NAME, TOKEN))
else:
logger.error("No MODE specified!")
sys.exit(1)
def start_handler(update: Update, context: CallbackContext):
# Creating a handler-function for /start command
logger.info("User {} started bot".format(update.effective_user["id"]))
update.message.reply_text("Hello from Python!\nPress /random to get random number")
def random_handler(update: Update, context: CallbackContext):
# Creating a handler-function for /random command
number = random.randint(0, 10)
logger.info("User {} randomed number {}".format(update.effective_user["id"], number))
update.message.reply_text("Random number: {}".format(number))
if __name__ == '__main__':
logger.info("Starting bot")
updater = Updater(token=TOKEN, use_context=True)
updater.dispatcher.add_handler(CommandHandler("start", start_handler))
updater.dispatcher.add_handler(CommandHandler("random", random_handler))
run(updater)