-
Notifications
You must be signed in to change notification settings - Fork 1
/
sendallmsg.py
executable file
·92 lines (77 loc) · 2.48 KB
/
sendallmsg.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
import telebot
import argparse
import sys
import time
import pymysql.cursors
from configobj import ConfigObj
##################
# parsing arguments
parser = argparse.ArgumentParser()
parser.add_argument("-c", dest='configfile', help="configfile", type=str, default="config.ini")
parser.add_argument('message', help="Message to send", type=str)
args = parser.parse_args()
##################
# read inifile
try:
config = ConfigObj(args.configfile)
apitoken = config.get('token')
db = config['dbname']
dbhost = config['dbhost']
dbport = config.get('dbport', '3306')
dbuser = config['dbuser']
dbpassword = config['dbpassword']
except:
print("Error in config.ini")
raise
##################
# connect to database
try:
connection = pymysql.connect(
host=dbhost,
user=dbuser,
password=dbpassword,
db=db,
port=int(dbport),
charset='utf8mb4',
autocommit='True')
cursor = connection.cursor()
except:
print("can not connect to database")
raise
##################
# get bot information
bot = telebot.TeleBot(apitoken)
try:
botident = bot.get_me()
botname = botident.username
botcallname = botident.first_name
botid = botident.id
try:
cursor.execute("insert into bot values ('%s','%s')" % (botid, botname))
except:
pass
except:
print("Error in Telegram. Can not find Botname and ID")
raise
##################
#
def sendtelegram(chatid, msg):
# try:
splitted_text = telebot.util.split_string(msg, 4096)
for text in splitted_text:
try:
bot.send_message(chatid, text, parse_mode="markdown")
except telebot.apihelper.ApiHTTPException as e:
print("ConnectionError - Sending again after 5 seconds!!!")
print("HTTP Error Code: {}".format(e.result))
time.sleep(5)
bot.send_message(chatid, text, parse_mode="markdown")
except telebot.apihelper.ApiTelegramException:
print("Telegram exception sending message to {}".format(chatid))
except:
print("ERROR IN SENDING TELEGRAM MESSAGE TO {}".format(chatid))
print("Error: {}".format(sys.exc_info()[0]))
cursor.execute("select chatid FROM user where botid = '%s' and chatid not in (select chatid from userblock)" % (botid))
allchat = cursor.fetchall()
for chatid in allchat:
sendtelegram(chatid[0],args.message)