Skip to content

Commit 285161a

Browse files
committed
Add telegram module
1 parent e227e2d commit 285161a

File tree

2 files changed

+97
-0
lines changed

2 files changed

+97
-0
lines changed

config/telegram.yml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
telegram:
2+
path: modules.network.telegram.Telegram
3+
enabled: false
4+
dependencies:
5+
python:
6+
- python-telegram-bot
7+
additional:
8+
- https://core.telegram.org/bots/tutorial#obtain-your-bot-token

modules/network/telegrambot.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
#!/usr/bin/env python
2+
# pylint: disable=unused-argument
3+
# This program is dedicated to the public domain under the CC0 license.
4+
5+
"""
6+
Simple Bot to reply to Telegram messages.
7+
8+
First, a few handler functions are defined. Then, those functions are passed to
9+
the Application and registered at their respective places.
10+
Then, the bot is started and runs until we press Ctrl-C on the command line.
11+
12+
Usage:
13+
Basic Echobot example, repeats messages.
14+
Press Ctrl-C on the command line or send a signal to the process to stop the
15+
bot.
16+
"""
17+
import logging
18+
import os
19+
20+
from telegram import ForceReply, Update
21+
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
22+
23+
# Enable logging
24+
logging.basicConfig(
25+
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
26+
)
27+
# set higher logging level for httpx to avoid all GET and POST requests being logged
28+
logging.getLogger("httpx").setLevel(logging.WARNING)
29+
30+
logger = logging.getLogger(__name__)
31+
32+
class TelegramBot:
33+
def __init__(self, **kwargs):
34+
"""
35+
Telegram Bot
36+
:param kwargs: token
37+
38+
Create a bot via Telegram's BotFather and get the token.
39+
40+
1. Search for BotFather in Telegram
41+
2. Start the BotFather
42+
3. Type /newbot
43+
4. Follow the instructions
44+
5. Copy the token (DON'T SHARE IT WITH ANYONE)
45+
6. Create an environment variable called TELEGRAM_BOT_TOKEN and set it to the token (can also be set in the config yaml)
46+
7. Run the script
47+
48+
"""
49+
# get token from environment variable
50+
self.token = os.getenv('TELEGRAM_BOT_TOKEN', kwargs.get('token', None))
51+
52+
"""Start the bot."""
53+
# Create the Application and pass it your bot's token.
54+
application = Application.builder().token(self.token).build()
55+
56+
# on different commands - answer in Telegram
57+
application.add_handler(CommandHandler("start", TelegramBot.start))
58+
application.add_handler(CommandHandler("help", TelegramBot.help_command))
59+
60+
# on non command i.e message - echo the message on Telegram
61+
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, TelegramBot.echo))
62+
63+
# Run the bot until the user presses Ctrl-C
64+
application.run_polling(allowed_updates=Update.ALL_TYPES)
65+
66+
# Define a few command handlers. These usually take the two arguments update and
67+
# context.
68+
@staticmethod
69+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
70+
"""Send a message when the command /start is issued."""
71+
user = update.effective_user
72+
await update.message.reply_html(
73+
rf"Hi {user.mention_html()}!",
74+
reply_markup=ForceReply(selective=True),
75+
)
76+
77+
@staticmethod
78+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
79+
"""Send a message when the command /help is issued."""
80+
await update.message.reply_text("Help!")
81+
82+
@staticmethod
83+
async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
84+
"""Echo the user message."""
85+
await update.message.reply_text(update.message.text)
86+
87+
88+
if __name__ == "__main__":
89+
bot = TelegramBot()

0 commit comments

Comments
 (0)