2020-07-16 19:17:57 +02:00
|
|
|
#!/usr/bin/env python
|
2020-10-31 16:33:34 +01:00
|
|
|
# pylint: disable=W0603
|
2020-07-16 19:17:57 +02:00
|
|
|
"""Simple Bot to reply to Telegram messages.
|
|
|
|
|
2021-02-01 17:59:39 +01:00
|
|
|
This is built on the API wrapper, see echobot.py to see the same example built
|
2020-07-16 19:17:57 +02:00
|
|
|
on the telegram.ext bot framework.
|
|
|
|
This program is dedicated to the public domain under the CC0 license.
|
|
|
|
"""
|
|
|
|
import logging
|
2020-10-31 16:33:34 +01:00
|
|
|
from typing import NoReturn
|
|
|
|
from time import sleep
|
|
|
|
|
2020-07-16 19:17:57 +02:00
|
|
|
import telegram
|
|
|
|
from telegram.error import NetworkError, Unauthorized
|
|
|
|
|
|
|
|
|
2020-10-31 16:33:34 +01:00
|
|
|
UPDATE_ID = None
|
2020-07-16 19:17:57 +02:00
|
|
|
|
|
|
|
|
2020-10-31 16:33:34 +01:00
|
|
|
def main() -> NoReturn:
|
2020-07-16 19:17:57 +02:00
|
|
|
"""Run the bot."""
|
2020-10-31 16:33:34 +01:00
|
|
|
global UPDATE_ID
|
2020-07-16 19:17:57 +02:00
|
|
|
# Telegram Bot Authorization Token
|
|
|
|
bot = telegram.Bot('TOKEN')
|
|
|
|
|
|
|
|
# get the first pending update_id, this is so we can skip over it in case
|
|
|
|
# we get an "Unauthorized" exception.
|
|
|
|
try:
|
2020-10-31 16:33:34 +01:00
|
|
|
UPDATE_ID = bot.get_updates()[0].update_id
|
2020-07-16 19:17:57 +02:00
|
|
|
except IndexError:
|
2020-10-31 16:33:34 +01:00
|
|
|
UPDATE_ID = None
|
2020-07-16 19:17:57 +02:00
|
|
|
|
|
|
|
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
echo(bot)
|
|
|
|
except NetworkError:
|
|
|
|
sleep(1)
|
|
|
|
except Unauthorized:
|
|
|
|
# The user has removed or blocked the bot.
|
2021-03-13 16:21:03 +01:00
|
|
|
UPDATE_ID += 1
|
2020-07-16 19:17:57 +02:00
|
|
|
|
|
|
|
|
2020-10-31 16:33:34 +01:00
|
|
|
def echo(bot: telegram.Bot) -> None:
|
2020-07-16 19:17:57 +02:00
|
|
|
"""Echo the message the user sent."""
|
2020-10-31 16:33:34 +01:00
|
|
|
global UPDATE_ID
|
2020-07-16 19:17:57 +02:00
|
|
|
# Request updates after the last update_id
|
2020-10-31 16:33:34 +01:00
|
|
|
for update in bot.get_updates(offset=UPDATE_ID, timeout=10):
|
|
|
|
UPDATE_ID = update.update_id + 1
|
2020-07-16 19:17:57 +02:00
|
|
|
|
|
|
|
if update.message: # your bot can receive updates without messages
|
2020-12-30 13:41:07 +01:00
|
|
|
if update.message.text: # not all messages contain text
|
|
|
|
# Reply to the message
|
|
|
|
update.message.reply_text(update.message.text)
|
2020-07-16 19:17:57 +02:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|