-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathbot.py
165 lines (142 loc) · 6.08 KB
/
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/enb python3
from datetime import datetime as DateTime
import argparse
import logging
import sys
import time
import telegram
from telegram import Update
from telegram.ext import ApplicationBuilder, filters, MessageHandler, CommandHandler, ContextTypes
from telegram.constants import ParseMode
import config
import utils
class DeckardBot():
def __init__(self):
self.get_options()
self.set_logger()
self.started_at = DateTime.now()
def get_options(self):
parser = argparse.ArgumentParser(
prog='bot',
description='PyDeckard Bot',
epilog='Text at the bottom of help',
)
parser.add_argument('-v', '--verbose', action='store_true')
args = parser.parse_args()
self.verbose = args.verbose
def set_logger(self):
self.logger = logging.getLogger('bot')
logging.basicConfig(
level=config.LOG_LEVEL,
format='%(asctime)s [%(name)s] %(levelname)s: %(message)s',
)
config.log(self.logger.info)
def trace(self, msg):
self.logger.info('bot asked to execute /status commamd')
if self.verbose:
print(msg)
async def command_status(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
self.trace('bot asked to execute /status commamd')
python_version = sys.version.split(maxsplit=1)[0]
text = '\n'.join([
config.BOT_GREETING,
f'Status is <b>OK</b>, running since {utils.since(self.started_at)}',
f'Python version is {python_version}',
])
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=text,
parse_mode=ParseMode.HTML,
)
self.trace(text)
async def command_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
self.trace('Received command /start')
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=config.BOT_GREETING,
parse_mode=ParseMode.HTML,
)
async def command_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
self.trace('Received command /help')
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=(
"Available commands:\n\n"
"<code>/start</code> : start intereaction with the bot\n"
"<code>/help</code> : Show commands\n"
"<code>/status</code> : Show status and alive time\n"
"<code>/zen</code> : Show the Zen of Python\n"
),
parse_mode=ParseMode.HTML,
)
async def command_zen(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
self.trace('Received command /zen')
text = '\n'.join(config.THE_ZEN_OF_PYTHON)
await context.bot.send_message(
chat_id=update.effective_chat.id,
text=text,
parse_mode=ParseMode.HTML,
)
async def welcome(self, update: Update, context):
self.trace('Received new user event')
new_member = update.message.new_chat_members[0]
self.trace(f'Waiting {config.WELCOME_DELAY} seconds until user completes captcha...')
time.sleep(config.WELCOME_DELAY)
membership_info = await context.bot.get_chat_member(update.message.chat_id, new_member.id)
if membership_info['status'] == 'left':
self.trace(f'Skipping welcome message, user {new_member.name} is no longer in the chat')
return
self.trace(f'send welcome message for {new_member.name}')
msg = None
if new_member.is_bot:
msg = f"{new_member.name} is a *bot*\\!\\! " \
"-> It could be kindly removed 🗑"
else:
if utils.is_bot(new_member):
await context.bot.delete_message(update.message.chat_id,
update.message.message_id)
if await context.bot.kick_chat_member(update.message.chat_id, new_member.id):
msg = (f"*{new_member.username}* has been banned because I "
"considered it was a bot. ")
else:
msg = f"Welcome {new_member.name}\\!\\! " \
"I am a friendly and polite *bot* 🤖"
if msg:
await update.message.reply_text(msg, parse_mode=telegram.constants.ParseMode('MarkdownV2'))
async def reply(self, update: Update, context: ContextTypes.DEFAULT_TYPE):
if config.bot_replies_enabled():
msg = update.message.text
reply_spec = utils.triggers_reply(msg) if msg else None
if reply_spec is not None:
self.trace(f'bot sends reply {reply_spec.reply}')
await update.message.reply_text(reply_spec.reply)
context.bot.send_message(
chat_id=update.message.chat_id,
text=reply_spec.reply
)
def run(self):
self.trace('Starting bot...')
application = ApplicationBuilder().token(config.TELEGRAM_BOT_TOKEN).build()
start_handler = CommandHandler('start', self.command_start)
application.add_handler(start_handler)
help_handler = CommandHandler('help', self.command_help)
application.add_handler(help_handler)
status_handler = CommandHandler('status', self.command_status)
application.add_handler(status_handler)
# Zen Command
application.add_handler(CommandHandler('zen', self.command_zen))
welcome_handler = MessageHandler(
filters.StatusUpdate.NEW_CHAT_MEMBERS,
self.welcome,
)
application.add_handler(welcome_handler)
reply_handler = MessageHandler(
filters.TEXT & (~filters.COMMAND),
self.reply,
)
application.add_handler(reply_handler)
self.trace('Bot is ready')
application.run_polling(poll_interval=config.POLL_INTERVAL)
if __name__ == "__main__":
bot = DeckardBot()
bot.run()