-
Notifications
You must be signed in to change notification settings - Fork 1
/
messengers.py
56 lines (46 loc) · 1.87 KB
/
messengers.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
import asyncio
from telegram.error import TimedOut, NetworkError, Forbidden
from bot_instance import bot
from utils import get_datetime_info
from dal import get_all_users_telegram_ids, remove_user_from_db
async def send_message_to_all_users(message: str, reply_markup=None, parse_mode=None) -> None:
"""
Sending Message To Bot Users
Args:
message: str
reply_markup
parse_mode
Returns:
None
"""
user_info = get_all_users_telegram_ids()
datetime_info = get_datetime_info()
year = datetime_info.get('year')
month = datetime_info.get('month')
day = datetime_info.get('day')
hour = datetime_info.get('hour')
minute = datetime_info.get('minute')
second = datetime_info.get('second')
print(f'Sending Message To Users On {year}-{month}-{day}\nTime: {hour}:{minute}:{second}')
for element in user_info:
try:
telegram_id = element[0]
user_database_id = element[1]
await bot.bot.send_message(chat_id=telegram_id, text=message, reply_markup=reply_markup, parse_mode=parse_mode)
print(f'Message sent to {telegram_id}')
except TimedOut:
print(f'Timeout error while sending message to {telegram_id}. Skipping user for now.')
except Forbidden:
# When the bot is blocked, delete the user from the database
await remove_user_from_db(user_database_id=user_database_id)
print(f'Failed to send message to {telegram_id} (bot blocked). User deleted!')
except NetworkError as e:
print(f'Network error: {e}. Retrying later for {telegram_id}.')
except Exception as e:
print(f'Unexpected error for {telegram_id}: {e}')
print()
if __name__ == '__main__':
message = """
"""
# Run the async function
asyncio.run(send_message_to_all_users(message, parse_mode='HTML'))