def user_in_chat(bot: TeleBot, chat_id, user_id): try: return bot.get_chat_member(chat_id, user_id).status != 'left' except telebot.apihelper.ApiException as e: if 'user not found' in e.args[0]: return False else: raise e
class DirectBot: def __init__(self): self.bot = TeleBot('YOUR TOKEN') self.myConnection = mysql.connector.connect(host="127.0.0.1", user='******', passwd='1111', db='YOURDB') self.cursor = self.myConnection.cursor() def main_function(self): @self.bot.message_handler(content_types=["new_chat_members"]) def handler_new_member(message): self.bot.send_message(message.chat.id, 'Добро пожаловать, {}! Чтобы занять очередь, напишите ' '"очередь" в чат, здоровья Вам и Вашим близким!' .format(message.from_user.first_name)) @self.bot.message_handler(content_types=['text']) def send_mess(message): self.cursor.execute("select max(level), max(queue) from sclick_schema.queue") for level, qu in self.cursor.fetchall(): self.last = level self.que = qu if message.text.upper() == 'ОЧЕРЕДЬ': def click(conn): mycursor = conn.cursor() sql = "INSERT INTO sclick_schema.queue (id_users, username, level, queue)" \ " VALUES (%s, %s, %s, %s) " val = ("{}".format(message.from_user.id), "{}".format(message.from_user.first_name), "{}".format(self.last + 1), "{}".format(self.que + 1)) mycursor.execute(sql, val) self.myConnection.commit() self.cursor.execute("select queue, level from sclick_schema.queue " "where id_users = {}".format(message.from_user.id)) for queue, i in self.cursor.fetchall(): self.bot.send_message(message.chat.id, " Добро пожаловать в систему, Ваша очередь = " " {} !".format(queue)) try: click(self.myConnection) except Exception: self.cursor.execute("select queue, level from sclick_schema.queue " "where id_users = {}".format(message.from_user.id)) for queue, level in self.cursor.fetchall(): self.bot.send_message(message.chat.id, " Ваша очередь = " " {} !".format(queue)) if message.text.upper() == "МИНУС ОЧЕРЕДЬ": us = self.bot.get_chat_member(message.chat.id, message.from_user.id) if us.status == "administrator" or us.status == "creator": self.cursor.execute("update sclick_schema.queue set queue = queue-1") self.myConnection.commit() self.bot.send_message(message.chat.id, 'очередь сдвинута на 1 пункт') else: self.bot.send_message(message.chat.id, 'данная команда вам недоступна') print(us.status) if message.text.upper() == 'СПИСОК': self.cursor.execute("select username, queue from sclick_schema.queue where queue between 0 and 4 " "order by queue") lst = "Список юзеров в очереди:\n\n" for usnm, ue in self.cursor.fetchall(): lst += f"{ue}. {usnm}\n" self.bot.send_message(message.chat.id, lst) if message.text.upper() == 'ПОЛНЫЙ СПИСОК': self.cursor.execute("select username, queue from sclick_schema.queue ") lst = "Список юзеров в очереди:\n\n" for usnm, ue in self.cursor.fetchall(): lst += f"{ue}. {usnm}\n" self.bot.send_message(message.chat.id, lst) def non_stop(self): while True: try: self.bot.polling(none_stop=True) except Exception as exepts: print(exepts) sleep(15)
message.chat.id, 'Эта команда доступна только администраторам!' ) @bot.message_handler( content_types=['text'], regexp='^(да)$', func=lambda message: ( message.chat.type in chat_types and message.reply_to_message and message.reply_to_message.text == ( 'Вы действительно хотите удалить данные по вашему чату?\n' '(Для продолжения ответьте "да" или "нет" на это сообщение' ' через "reply"(ответить))' ) and (bot.get_chat_member(message.chat.id, message.from_user.id).status == 'creator' or bot.get_chat_member(message.chat.id, message.from_user.id).status == 'administrator') ) ) def delete_chat(message): db.db_delete(message.chat.id) bot.send_message(message.chat.id, 'Данные по карме в вашем чате удалены') @bot.message_handler( content_types=['text'], regexp=r'^([+-]|спасибо\W*)$', func=lambda message: (message.chat.type in chat_types and message.reply_to_message)
class BotUtil(TeleBot): def __init__(self, token, creator=None): super().__init__(token) self.bot = TeleBot(token) self.__group_admins = ['administrator', 'creator'] self.__creator = creator def edit_message(self, message_text, chat_id, message_id, reply_markup=None, parse_mode=None): return self.bot.edit_message_text(chat_id=chat_id, message_id=message_id, text=message_text, reply_markup=reply_markup, parse_mode=parse_mode) def reply(self, chat_id, message_text, message_id, reply_markup=None, parse_mode=None): return self.bot.send_message(chat_id, message_text, reply_to_message_id=message_id, reply_markup=reply_markup, parse_mode=parse_mode) @staticmethod def get_link(name, user_id): return '<a href="tg://user?id={}">{}</a>'.format(user_id, name) def is_admin(self, chat, user): chat_member = self.bot.get_chat_member(chat, user) if chat_member.status in self.__group_admins: return True else: return False def __admin_checks(self, chat, user, admin_user): if chat.type == "private": self.bot.send_message( chat.id, "Административные команды не работают в личных сообщениях.") return False if self.is_admin(chat.id, user.id): self.bot.send_message(chat.id, "Вы пытаетесь ограничить администратора.") return False if not self.is_admin(chat.id, admin_user.id): self.bot.send_message(chat.id, "Вы не администратор.") return False if not self.is_admin(chat.id, self.bot.get_me().id): self.bot.send_message(chat.id, "Я не администратор.") return False return True def mute(self, chat, user, admin_user, for_date=0, reason=""): if not self.__admin_checks(chat, user, admin_user): return now_time = int(time.time()) until_date = now_time + for_date time_text = "секунд" date_text = for_date if for_date > 60: date_text = "минут" time_text = str(for_date / 60) elif for_date > 3600: date_text = "часов" time_text = str(for_date / 3600) elif for_date > 86400: date_text = "дней" time_text = str(for_date / 86400) tts = 'Пользователь {} ограничен на {} {}.'.format( self.get_link(user.first_name, user.id), time_text, date_text) if for_date < 60: tts = "Пользователь {} ограничен навсегда.".format( self.get_link(user.first_name, user.id)) tts += "\nПричина: {}".format(reason) self.bot.restrict_chat_member(chat.id, user.id, until_date=until_date) self.bot.send_message(chat.id, tts, parse_mode="HTML") def ban(self, chat, user, admin_user, for_date=0, reason=""): if not self.__admin_checks(chat, user, admin_user): return now_time = int(time.time()) until_date = now_time + for_date time_text = "секунд" date_text = for_date if 60 < for_date < 3600: date_text = "минут" time_text = str(for_date / 60) elif 3600 < for_date < 86400: date_text = "часов" time_text = str(for_date / 3600) elif for_date > 86400: date_text = "дней" time_text = str(for_date / 86400) tts = 'Пользователь {} заблокирован на {} {}.'.format( self.get_link(user.first_name, user.id), time_text, date_text) if for_date < 60: tts = "Пользователь {} заблокирован навсегда.".format( self.get_link(user.first_name, user.id)) tts += "\nПричина: {}".format(reason) self.bot.kick_chat_member(chat.id, user.id, until_date=until_date) self.bot.send_message(chat.id, tts, parse_mode="HTML") def report(self, text, quiet=False): if self.__creator: if not quiet: print(text) return self.bot.send_message(self.__creator, text) def send_message(self, chat_id, text, disable_web_page_preview=None, reply_to_message_id=None, reply_markup=None, parse_mode="HTML", disable_notification=None, timeout=None): super().send_message(chat_id, text, disable_web_page_preview, reply_to_message_id, reply_markup, parse_mode, disable_notification, timeout)