-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
126 lines (91 loc) · 3.02 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
import json
import datetime as dt
import telebot
from telebot import apihelper
### https://api.telegram.org/botBOT_ID/getupdates
### Settings
try:
with open("settings.json") as f:
bot_settings = json.load(f)
except Exception:
bot_settings = {
"group_id": None,
"last_sent_poll_id": None,
"last_manual_poll_time": 0,
"bot_id": None,
"owner_id": None,
}
apihelper.SESSION_TIME_TO_LIVE = 5 * 60
bot = telebot.TeleBot(bot_settings.bot_id)
### Command and update handlers
@bot.message_handler(commands=["poll"])
def poll_reply(message: telebot.types.Message):
save_message(message)
if message.chat.type != "private":
try:
bot.unpin_chat_message(
bot_settings["group_id"], bot_settings["last_sent_poll_id"]
)
except Exception:
pass
chat_id = message.chat.id
reply = send_poll(chat_id)
bot_settings["last_manual_poll_time"] = dt.datetime.timestamp(dt.datetime.now())
save_message(reply)
@bot.message_handler(commands=["help"])
def reply_to_help(message: telebot.types.Message):
save_message(message)
reply = bot.send_message(
message.chat.id,
"""Я ежедневно высылаю в группу опросник с вопросом "будем ли мы сегодня играть".
Допустимые команды:
/help - эта подсказка
/poll - инициировать новый опрос""",
)
save_message(reply)
### Other functions
def save_message(message: telebot.types.Message):
print(
f"{dt.datetime.fromtimestamp(message.date)}: сообщение: {message.text} от {message.from_user.username}"
)
def save_settings_to_file():
with open("settings.json", "w") as f:
json.dump(bot_settings, f, ensure_ascii=False)
def poll_answers():
try:
with open("answers.json", "r") as f:
answers = json.loads(f)
except Exception:
answers = ["Да", "Нет", "Не знаю"]
with open("answers.json", "w") as f:
json.dump(answers, f, ensure_ascii=False)
return answers
def send_poll(chat_id: int):
sent_poll = bot.send_poll(
chat_id,
"Будем играть сегодня?",
poll_answers(),
False,
)
if bot_settings["last_sent_poll_id"] != 0:
try:
bot.unpin_chat_message(chat_id, bot_settings["last_sent_poll_id"])
except Exception:
pass
bot_settings["last_sent_poll_id"] = sent_poll.message_id
bot.pin_chat_message(chat_id, sent_poll.message_id)
save_settings_to_file()
return sent_poll
def notifyOnStartup():
bot.send_message(
bot_settings.owner_id,
"""Бот запущен""",
)
if bot_settings["group_id"] != None:
print("bot polling started")
notifyOnStartup()
bot.infinity_polling()
else:
save_settings_to_file()
print("Group ID not found. Fill in group_id in bot_settings.json and restart.")
print("Exiting.")