-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram_bot.py
116 lines (98 loc) · 3.74 KB
/
telegram_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/python3
import logging
import signal
import requests
import time
import os
import configparser
import sys
import argparse
def millis():
return round(time.time() * 1000)
# Let's prepare loggin system. Not necessary and can be removed alone with all <logger.> calls
# Create format for the log messages
logFormatter = logging.Formatter("%(asctime)s [%(levelname)-4.4s] %(message)s")
logger = logging.getLogger("tele_bot")
# Let's capture all logger messages
logger.setLevel( logging.INFO )
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
# Constole will print only warnings and errors
consoleHandler.setLevel(logging.WARNING)
logger.addHandler(consoleHandler)
fileHandler = logging.FileHandler("telegram_bot.log")
fileHandler.setFormatter(logFormatter)
# Log file will contain all messages generated by the logger
fileHandler.setLevel(logging.INFO)
logger.addHandler(fileHandler)
# Simple function for sending message to specific chat
def telegram_send(token, msg, chat_id=None):
# If no sender, just send to group chat, or personalized chat
if chat_id is None:
chat_id = main_chat_id
if chat_id is None or token is None:
return
host = "https://api.telegram.org/bot" + token + "/sendMessage"
try:
result = requests.post(host, data = {"chat_id": chat_id, "text": msg, "disable_notification": "1"}, timeout=1)
result = result.json()
except:
result = None
# print(result)
return result
# Simple function to read updates for specific bot
def telegram_update(token, offset=0):
host = "https://api.telegram.org/bot" + token + "/getUpdates"
try:
result = requests.post(host, data = {"offset": str(offset)}, timeout=2)
result = result.json()
except:
result = None
return result
def process_text_message(token, msg, chat_id):
# This is for example, just some emoji icons to use in a text messages
green_emoji = u'\U0001F49A'
blue_emoji = u'\U0001F499'
red_emoji = u'\U0001F4A5'
logger.info( msg )
telegram_send( token, blue_emoji + msg, chat_id )
telegram_bot_token = None
main_chat_id = None
config = configparser.ConfigParser()
if len( config.read( 'config.ini')) > 0:
if config.has_option('main', 'telegram_bot_token'):
telegram_bot_token = config.get('main', 'telegram_bot_token')
if config.has_option('main', 'main_chat_id'):
main_chat_id = config.get('main', 'main_chat_id' )
exit_requested = False
def exit_gracefully(signum, frame):
global exit_requested
logger.error("SIGTERM received")
exit_requested = True
signal.signal(signal.SIGINT, exit_gracefully)
signal.signal(signal.SIGTERM, exit_gracefully)
logger.info("Bot started")
# Receive all unconfirmed messages
update_id = 0
while not exit_requested:
result = telegram_update(telegram_bot_token, offset = update_id)
if result is not None and result['result'] is not None:
for record in result['result']:
update_id = int(record['update_id']) + 1
if "message" in record:
branch = "message"
elif "channel_post" in record:
branch = "channel_post"
else:
# If the update information doesn't contain any message Skip
continue
if "text" not in record[branch]:
# If the update information doesn't contain any text in the message Skip
continue
text = record[branch]['text']
chat = record[branch]['chat']['id']
if branch == "message":
sender = record[branch]['from']['id']
else:
sender = record[branch]['sender_chat']['id']
process_text_message( telegram_bot_token, text, chat )