def cat_all_musice(message): try: all_musice = get_all_music_list() bot.send_message(message.chat.id, '服务器总计:{} 部资源,请大家踊跃上传高质量音乐'.format(len(all_musice))) except Exception as e: logger.error(e) return
def callback_text(call): call_query_id = call.id try: text = call.data[2:] bot.answer_callback_query(call_query_id, text=text, show_alert=False) except Exception as e: logger.error(str(e))
def run(self): while self._running: try: task, args, kwargs = self.queue.get(block=True, timeout=.5) self.continue_event.clear() self.received_task_event.clear() self.done_event.clear() self.exception_event.clear() logger.debug("Received task") self.received_task_event.set() task(*args, **kwargs) logger.debug("Task complete") self.done_event.set() except Queue.Empty: pass except Exception as e: logger.error( type(e).__name__ + " occurred, args=" + str(e.args) + "\n" + traceback.format_exc()) self.exc_info = sys.exc_info() self.exception_event.set() if self.exception_callback: self.exception_callback(self, self.exc_info) self.continue_event.wait()
def read(self, user_id: int) -> UserInfo: if not self.exists(user_id): logger.error("User %s does not exist", user_id) raise KeyError('User does not exist') info = self._storage.read(str(user_id)) # noinspection PyTypeChecker return UsersRepository._to_user_info(info, user_id)
def leave_group(message): try: bot.send_message(message.chat.id, '我要走了,各位小姐姐拜拜') bot.leave_chat(message.chat.id) except Exception as e: logger.error(e) return
def del_lottery_list(message): try: un = str(message.from_user.id) logger.info(message.chat) if message.chat.type == 'private': if un not in is_admin(): bot.send_message( message.chat.id, "你好:\n由于你权限不够还不能操作额\n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面", parse_mode='Markdown') else: r = join.del_list() bot.reply_to(message, r) else: if un not in is_admin(): msg_id = bot.send_message( message.chat.id, "你好:\n由于你权限不够还不能操作额\n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面", parse_mode='Markdown').message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() else: r = join.del_list() msg_id = bot.reply_to(message, r).message_id timer = threading.Timer(5, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def handle_start(message): try: bot.send_message(message.chat.id, "🌹欢迎来到天山一枝梅的音乐空间\n你可以直接输入歌名查找", reply_markup=bottom_markup()) except Exception as e: logger.error(e) return
def send_list(message): try: logger.info(message.chat) if message.chat.type == 'private': un = message.from_user.username bot.send_chat_action(message.chat.id, 'typing') r = join.read_list(un) count = -1 for count, line in enumerate(open("list", 'r')): pass count += 1 rr = u'%s \n\n 目前共有%s人参与抽奖哦' % (r, count) msg_id = bot.reply_to(message, rr).message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() else: bot.send_chat_action(message.chat.id, 'typing') markup = types.InlineKeyboardMarkup() btn = types.InlineKeyboardButton('戳这里!', url='https://t.me/Bibo_dear_bot') markup.add(btn) msg_id = bot.send_message(chat_id=message.chat.id, text=u'为了防止刷屏,请在私聊中使用此命令哦~', reply_markup=markup).message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def get_user_info(message): try: logger.info(message.text) nick_name = get_nickname(message) if message.from_user.username: msg_id = bot.send_message( message.chat.id, "亲爱的❤️{} ❤️你好\n你的 Chat_Id = {}\nUsername是 {} \n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面\n" " 10秒后自动删除!\n".format(nick_name, message.from_user.id, message.from_user.username), parse_mode='Markdown').message_id else: msg_id = bot.send_message( message.chat.id, "亲爱的 {} 你好\n你的 Chat_Id是 = {}\nUsername 还没设置 \n 10秒后自动删除!". format(message.from_user.first_name, message.from_user.id)).message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def say_welcom(message): try: if message.new_chat_members: frist_name = message.new_chat_member.first_name last_name = message.new_chat_member.last_name if frist_name and last_name and frist_name != last_name: nick_name = frist_name + last_name else: nick_name = frist_name logger.info(message.new_chat_member) msg_id = bot.send_message( message.chat.id, "💋聪明`机智`能干`活泼`又机灵的小霸霸\n代表本群所有人热烈欢迎新成员: {} 加入大家庭\n🌺 کارب عزیز 🌺\n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面" .format(nick_name), parse_mode='Markdown').message_id else: frist_name = message.left_chat_member.first_name last_name = message.left_chat_member.last_name if frist_name and last_name and frist_name != last_name: nick_name = frist_name + last_name else: nick_name = frist_name logger.info(message.left_chat_member) msg_id = bot.send_message( message.chat.id, '本群精英:{} 离开了我们团队,一路走好,恭喜发财!'.format(nick_name)).message_id timer = threading.Timer(20, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def handle_start(message): try: keyboard = types.InlineKeyboardMarkup() callback_button_menu = types.InlineKeyboardButton( text="讲段子", callback_data="讲段子", ) callback_button_song = types.InlineKeyboardButton(text='天气状况', callback_data='天气状况') # callback_button_news = types.InlineKeyboardButton(text='今日新闻', callback_data='今日新闻') callback_button_phones = types.InlineKeyboardButton( text='电话簿', url='https://www.feituan.ph/index.php?cid=&ccid=9') # callback_button_cars = types.InlineKeyboardButton(text='日常修车', url='t.me/openporn') keyboard.add( callback_button_menu, callback_button_song, callback_button_phones, ) msg_id = bot.send_message(message.chat.id, "欢迎使用自助机器人!", reply_markup=keyboard).message_id timer = threading.Timer(30, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def exchange(message): try: logger.info(message.chat) content = get_exchange() bot.send_message(message.chat.id, content) except Exception as e: logger.error(e) pass
def handle_start(message): try: bot.send_message(message.chat.id, "🌹欢迎来到天上一枝梅的音乐空间\n", reply_markup=bottom_markup()) except Exception as e: logger.error(e) pass
def callback_menu(call): try: logger.info(call.data) callback_id = call.message.json['chat']['id'] msg_id = bot.send_message(callback_id, get_joke()).message_id timer = threading.Timer(300, bot.delete_message, (callback_id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def update(self, *args, msg=None, hand=None, data=None, **kwargs): order = Order.filter_by(user_id=msg.from_user.id, state=StateOrder.not_send).first() if not order: order = Order.create(user_id=msg.from_user.id, number=str(msg.message.message_id)) ware = Ware.get(data) if not ware: logger.error(f'Товар {data} не найден') return try: order_item = order.add_item(ware) except Exception as e: hand.send_cb(msg, str(e), show_alert=False) return self.answer(*args, msg=msg, hand=hand, ware=ware, order=order, order_item=order_item, **kwargs)
def callback_menu(call): try: logger.info(call.from_user) logger.info(call.data) callback_id = call.message.json['chat']['id'] msg_id = bot.send_message( callback_id, '今日推荐:{},\n{}\n{} \n 60秒自动删除!'.format( get_news()['title'], get_news()['source'], get_news()['cover'])).message_id timer = threading.Timer(60, bot.delete_message, (callback_id, msg_id)) timer.start() except Exception as e: logger.error(e)
def ban_user(message): try: logger.info(message.text) user_id = message.reply_to_message.from_user.id if str(message.from_user.id) in is_admin() and user_id not in is_admin( ) and user_id != bot.get_me().id: bot.kick_chat_member(message.chat.id, user_id) else: bot.send_message(message.chat.id, '如果本`bot` 没猜错 多半是你 权限不够,加油吧骚年', parse_mode='Markdown') bot.send_audio() except Exception as e: logger.error(e) pass
def user_status(message): try: logger.info(message.chat) username = get_nickname(message) chat_id = message.from_user.id num = search_signs(chat_id) msg_id = bot.reply_to( message, '{}:您总共签到:{} 次,很棒棒额,请再接再厉,20秒自毁以启动'.format(username, num)).message_id timer = threading.Timer(20, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def get_user_input_name(message): try: if len(message.text) > 20: msg = bot.reply_to(message, '名字太长,请重新输入') bot.register_next_step_handler(msg, get_user_input_name) elif message.text.strip().upper() == 'Q': bot.reply_to(message, '退出成功,你现在可以输入歌名进行快速搜索额') return else: input_list = message.text.split() msg = bot.reply_to(message, '请拖入音频文件:') bot.register_next_step_handler(msg, save_user_input_file, input_list) except Exception as e: logger.error(e) bot.reply_to(message, '操作失败') return
def execution_test_case(message): try: logger.info(message.chat) user_id = str(message.from_user.id) if user_id in is_admin(): environment = re.search('execution_case_(.*)_over', message.text).group(1) if '_' in environment: en = environment.split('_')[0] with open(ENV_FILE_PATH, 'a', encoding='utf-8') as f: f.write('|'.join(environment.split('_'))) f.write('\r') else: en = environment with open(ENV_FILE_PATH, 'a', encoding='utf-8') as f: f.write(''.join(environment)) f.write('\r') id = bot.send_message( message.chat.id, '霸霸正在拼命执行{}的所以测试用例,请稍等片刻...😅😅...'.format(en)).message_id timer1 = threading.Timer(300, bot.delete_message, (message.chat.id, id)) timer1.start() os.chdir(WORK_PATH) os.system('python3 run_api_case.py') # 再推送到群里 time.sleep(10) with open( '{}/{}'.format(TEST_CASE['case_result_file_path'], TEST_CASE['case_result_file_name']), 'rb') as f: msg_id = bot.send_document(message.chat.id, data=f).message_id os.chdir(PATH) timer = threading.Timer(300, bot.delete_message, (message.chat.id, msg_id)) timer.start() else: msg_id = bot.send_message( message.chat.id, "你好:\n由于你权限不够还不能操作额\n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面", parse_mode='Markdown').message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def join_lottery(message): try: logger.info(message.chat) if message.chat.type == 'private': un = message.from_user.username r = join.add_in(un) bot.reply_to(message, r) else: un = message.from_user.username r = join.add_in(un) msg_id = bot.reply_to(message, r).message_id timer = threading.Timer(15, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def callback_menu(call): try: data = get_weather() logger.info(call.from_user) logger.info(call.data) callback_id = call.message.json['chat']['id'] msg_id = bot.send_message( callback_id, "城市{} 温度:{} {} \n风向:{}{} 湿度:{} 时间:{}\n 60秒后自动删除!".format( data['address'], data['temp'], data['weather'], data['windDirection'], data['windPower'], data['humidity'], data['reportTime'])).message_id timer = threading.Timer(60, bot.delete_message, (callback_id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def bottom_markup(): try: markup = InlineKeyboardMarkup() markup.row_width = 1 markup.one_time_keyboard = 2 markup.add(InlineKeyboardButton(type_list[0], callback_data='type_{}'.format(type_list[0])), InlineKeyboardButton(type_list[1], callback_data='type_{}'.format(type_list[1])), InlineKeyboardButton(type_list[2], callback_data='type_{}'.format(type_list[2])), InlineKeyboardButton(type_list[3], callback_data='type_{}'.format(type_list[3])), InlineKeyboardButton(type_list[4], callback_data='type_{}'.format(type_list[4])), InlineKeyboardButton(type_list[5], callback_data='type_{}'.format(type_list[5])), InlineKeyboardButton(type_list[6], callback_data='type_{}'.format(type_list[6])), InlineKeyboardButton('我要上传/upload', callback_data='upload'), InlineKeyboardButton('联系客服/Customer service', url=my_url)) return markup except Exception as e: logger.error(e) return
def send_message(receiver: User, text=None, photo=None, markup=None): try: if photo: self.bot.send_photo(receiver.chat_id, caption=text, photo=photo, reply_markup=markup) else: self.bot.send_message(receiver.chat_id, text, reply_markup=markup) return True except Exception as e: err_text = f"User @{receiver.username} {receiver.chat_id} didn't receive message - {e}" logger.error(err_text) self.bot.send_message(chat_id=admin_chat_id, text=err_text) receiver.is_blocked = True receiver.save()
def musin(message): try: name = ''.join(message.text.strip()) music_list = get_all_music_list() for one in music_list: if name + '.mp3' == one[0] or name + '.m4a' == one[0]: msg_id = bot.reply_to(message, '正在发送....').message_id with open(one[1], 'rb')as f: bot.send_audio(message.chat.id, f, caption=name + "<a href='{}'>{}</a>".format(bot_url, '@all_musices_bot'), parse_mode='HTML', timeout=20) bot.delete_message(message.chat.id, msg_id) return else: pass bot.send_message(message.chat.id, '你输入的歌名不存在,请先上传') except Exception as e: logger.error(e) return
def execution_lottery(message): try: un = message.from_user.username logger.info(message.chat) f = open('admin_list', 'r') l = f.read() if l.find('%s' % un) == -1: msg_id = bot.send_message( message.chat.id, "你好:\n由于你权限不够还不能操作额\n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面", parse_mode='Markdown').message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() else: code, r = join.get_lottery() bot.reply_to(message, r) except Exception as e: logger.error(e) pass
def check_order_log(message): try: logger.info(message.chat) if str(message.from_user.id) in is_admin(): with open( '{}/{}'.format(CHECK_ORDER['log_path'], CHECK_ORDER['log_name']), 'rb') as f: msg_id = bot.send_document(message.chat.id, data=f).message_id else: msg_id = bot.send_message( message.chat.id, "你好:\n由于你权限不够还不能操作额\n" "你可以把本[bot](t.me/@Bibo_dear_bot)加到[你的群组](t.me/YoutubeChannelsBot?startgroup=true)里面", parse_mode='Markdown').message_id timer = threading.Timer(10, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def get_help(message): try: logger.info(message.chat) if message.chat.type == 'private': bot.send_chat_action(message.chat.id, 'typing') bot.send_message( message.chat.id, "/join_lottery - 加入抽奖\n/list_lottery- 查看名单\n/lottery - 抽奖[admin]\n/clear_game_list - 清空名单[admin]\n" ) else: bot.send_chat_action(message.chat.id, 'typing') msg_id = bot.send_message( message.chat.id, "/join_lottery - 加入抽奖\n/list_lottery- 查看名单\n/lottery - 抽奖[admin]\n/clear_game_list - 清空名单[admin]\n" ).message_id timer = threading.Timer(30, bot.delete_message, (message.chat.id, msg_id)) timer.start() except Exception as e: logger.error(e) pass
def set_black_list(message): try: logger.info(message.text) user_id = message.reply_to_message.from_user.id if str(message.from_user.id) in is_admin(): if user_id not in is_admin() and user_id != bot.get_me().id: with open(black_path, 'a', encoding='utf-8') as f: f.write('|' + str(user_id)) bot.restrict_chat_member(message.chat.id, user_id, until_date=time.time() + 600) bot.send_message(message.chat.id, '禁言10分钟,警告一次') else: bot.send_message(message.chat.id, '你不能禁言此用户额') else: bot.send_message(message.chat.id, '如果本`bot` 没猜错 多半是你 权限不够,加油吧骚年', parse_mode='Markdown') except Exception as e: logger.error(e) pass
def send_music_file(call): try: pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, password=123456) redis_db = redis.Redis(connection_pool=pool) if redis_db.get('music_timer'): bot.answer_callback_query(call.id, '操作太频繁,正在拼命准备资源,请稍等片刻.....', show_alert=True, cache_time=5) else: redis_db.set('music_timer', 'mutton', ex=2) if call.data.startswith('music_'): music_type = re.findall(r'^music_(.*)_type_(.*)', call.data)[0] path = os.path.abspath(os.path.join(os.getcwd(), music_type[1])) msg_id = bot.reply_to(call.message, '正在发送....').message_id with open(path + '/' + music_type[0], 'rb')as f: bot.send_audio(call.message.chat.id, f, caption=music_type[0].split('.')[0] + "<a href='{}'>{}</a>".format(bot_url, '@all_musices_bot'), parse_mode='HTML', timeout=20) bot.delete_message(call.message.chat.id, msg_id) elif call.data.startswith('type_'): music_type: str = re.search(r'^type_(.*)', call.data).group(1) music_list = get_all_music(music_type) mark = InlineKeyboardMarkup() for one in random.sample(music_list, 10): mark.add(InlineKeyboardButton(text=one, callback_data='music_{}_type_{}'.format(one, music_type))) mark.add(InlineKeyboardButton(text='返回目录', callback_data='go_last'), InlineKeyboardButton(text='换一批', callback_data='type_{}'.format(music_type))) bot.edit_message_text(music_type + '随机10首', chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=mark) elif call.data == 'go_last': bot.edit_message_text('音乐机器人', chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=bottom_markup()) elif call.data == 'upload': msg = bot.send_message(call.message.chat.id, '请输入上传类型 歌曲名称空格隔开,\n如:热门DJ舞曲 狂浪\n 输入:q 退出输入模式!\nPlease enter the type of upload and the name of the song, \nseparated by a space,For Example: Englishsongs happyBirthday') bot.register_next_step_handler(msg, get_user_input_name) except Exception as e: logger.error(e) return
photo = open('media/academic_cal.png', 'rb') bot.send_photo(message.chat.id, photo) # bot.send_photo(photo ='academic_cal.png') elif message.text == 'Data': mestext = bot.send_message(message.chat.id, "Send me excel file!") #bot.message_handler(func=lambda message: message.document.mime_type == 'application/' #'vnd.openxmlformats-officedocument.spreadsheetml.sheet', content_types=['document']) bot.register_next_step_handler(mestext, test_get_file) bot.send_message(message.chat.id, "Got you)") else: bot.send_message(message.chat.id, "Sorry! Retry again later\n Press /start \n[-%s-] is not available now(" % message.text) except Exception as e: bot.reply_to(message, 'Oooops! Press /start to go Main_menu') if __name__ == '__main__': while True: try: bot.polling(none_stop=True) except Exception as e: logger.error(e) time.sleep(15) bot.polling()