This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
telegram.py
72 lines (52 loc) · 1.85 KB
/
telegram.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# pylint: disable=C0321, C0114, W0702, C0103, C0301, R1710, W0603, W0621
"""
Adds support for Telegram Bot messaging.
To enable, provide a TELEGRAM_TOKEN environment variable.
"""
import logging
from os import getenv
from asyncio import sleep
from aiogram import Bot, Dispatcher, types
from aiogram.utils import exceptions, executor
TELEGRAM_TOKEN = getenv('TELEGRAM_TOKEN')
TELEGRAM_USERS = getenv('TELEGRAM_USERS').split(',')
logging.basicConfig(level=logging.INFO)
log = logging.getLogger('telegam')
log.info("Module loaded.")
bot = Bot(token=TELEGRAM_TOKEN, parse_mode=types.ParseMode.HTML)
dp = Dispatcher(bot)
async def send_message(user_id: int, text: str, disable_notification: bool = False) -> bool:
"""
Safe messages sender
:param user_id:
:param text:
:param disable_notification:
:return:
"""
try:
await bot.send_message(user_id, text, disable_notification=disable_notification)
except exceptions.BotBlocked:
log.error("Target [%s]: blocked by user", user_id)
except exceptions.ChatNotFound:
log.error("Target [%s]: invalid user ID", user_id)
except exceptions.RetryAfter as e:
log.error("Target [%s]: flood limited, sleeping %d.",
user_id, e.timeout)
await sleep(e.timeout)
return await send_message(user_id, text)
except exceptions.UserDeactivated:
log.error("Target [ID:%s]: user is deactivated", user_id)
except exceptions.TelegramAPIError:
log.exception("Target [ID:%s]: failed", user_id)
else:
log.info("Target [ID:%s]: success", user_id)
return True
return False
def send(message="RING"):
"""
Sends a message to the envrionment-programmed recipients
Keyword arguments:
message -- Any string
"""
for t in TELEGRAM_USERS:
executor.start(dp, send_message(t, message))