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 handle_new_user(message): if not bot.user_exists(message.chat.id): logger.info("Launching sign_up scenario from main.py") sign_up.launch(message) return True else: return False
def send_reminder_for(from_user_id, _id=None): if _id[:2] == 'su': l = util_db.get_survey(survey_id=_id) elif _id[:2] == 'ev': l = util_db.get_event(event_id=_id) frichtle = util_db.get_frichtle() username = util_db.get_frichtle(user_id=from_user_id).get_inline_str() for f in frichtle: if f.user_id == from_user_id: continue if isinstance(l, Survey): needs = util_db.check_survey_response(user_id=f.user_id, survey_id=_id) == None markup = markups.selection.new_survey_alert() text = "{} bittet um Rückmeldung für folgende Umfrage:\n".format(username) + str(l) elif isinstance(l, Event): needs = util_db.check_attendance(user_id=f.user_id, event_id=_id) == 1 markup = markups.selection.new_event_alert() text = "{} bittet um Rückmeldung für folgenden Termin:\n".format(username) + str(l) else: needs = False if needs: bot.send_message(f.user_id, text=text, reply_markup=markup) logger.info("Send reminder for: {}".format(str(l).replace("\n", ";"))) return
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 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 __join_button_pressed(call): if call.message.message_id in instances: user_id, activities = instances[call.message.message_id] pointer = __parse_join_activity_data(call.data) activity_id = activities[pointer].id p = False if is_participating(user_id, activity_id): logger.info(f"Unlisting user from activity #{activity_id}") quit_activity(user_id, activity_id) p = False else: logger.info(f"Enlisting user in activity #{activity_id}") participate_in_activity(user_id, activity_id) p = True try: frontend.edit_message_reply_markup( chat_id=call.message.chat.id, message_id=call.message.message_id, reply_markup=__activity_markup(activities, pointer, p)) except apihelper.ApiException as e: print(e) frontend.answer_callback_query(call.id)
def set_attendance_to_event(event_id, user_id, att): if att not in [1, 2, 3]: return db.events.update_one({"_id": event_id}, {"$set": {f"attendance._{user_id}": att}}) f = get_frichtle(user_id=user_id) logger.info(f"Set attendance={att} for " + f.name + " for event " + event_id) return
def add_event(ev): ev.attendance = {k: 1 for k in get_from_all_frichtle(info="user_id")} ev = ev.to_json() ev["_id"] = ev["event_id"] db.events.insert_one(ev) logger.info("Added Event: {}".format(str(ev).replace("\n", ";"))) return
def atualizar_db(): """Atualizar banco de dados buscando 5 posts""" posts = bloggerapi.get_posts_blog(webSite, api_key, num=5) posts = json.loads(posts) logger.info('Atualizando db com os posts:\n {}'.format(posts)) for post in posts.get('items'): idPost = int(post['id']) data = post['published'][0:10] url = post['url'] autor = post['author']['displayName'] etiquetas = ', '.join(post['labels']) titulo = post['title'] publicado = 0 if not existe_id(idPost): with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute( """ INSERT INTO publicacoes (data_publicacao, url, autor, etiquetas, titulo, publicado, idPost) VALUES (?, ?, ?, ?, ?, ?, ?)""", (data, url, autor, etiquetas, titulo, publicado, idPost)) conn.commit() cursor.close() logger.info("Banco de dados atualizado")
def get_posts_blog(url, api_key, num=1): """Retorna entidade post :param url: link com http ou https :param api_key: chave api google blogger :param num: quantidade de posts""" logger.info("get_posts_blog\nurl={}\napi_key={}\nnum={}".format( url, api_key, num)) if 'http' not in url: raise KeyError('A url precisa conter http ou https') blogID = get_id_blog(url, api_key) resposta = None num = str(num) if blogID is not None: try: url = 'https://www.googleapis.com/blogger/v3/blogs/'\ +blogID+'/posts?fetchBodies=false&fetch\ Images=false&maxResults=' + num + '&orderBy=published&\ status=live&view=READER&key=' +api_key resposta = requests.get(url).content.decode('utf-8') logger.info("Resposta ao buscar posts {}".format(resposta)) if resposta: return resposta except HTTPError: return None
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 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 __activities_near_button_pressed(call): alert_text = None activities = bot.suggest_activities(call.message.chat.id) logger.info("Serving activity_viewer with activities nearby") if not send_activities(call.message, activities, alert_text): alert_text = "Не найдено ни одно достаточно близкое к Вам мероприятие" frontend.answer_callback_query(call.id, alert_text)
def __find_button_pressed(call): alert_text = None activities = bot.activities_by_user(call.message.chat.id) logger.info("Serving activity_viewer with user's activities") if not send_activities(call.message, activities, alert_text): alert_text = "Вы не подписаны ни на одно мероприятие" frontend.answer_callback_query(call.id, alert_text)
def remove_event(event_id=None, ev=None): if event_id is None: event_id = ev.event_id event = db.events.find_one_and_delete({"_id": event_id}) if event: logger.info(f"Removed Event: {event['description']}") return
def remove_survey(survey_id=None, survey=None): if survey_id is None: survey_id = survey.survey_id survey = db.survey.find_one_and_delete({"_id": survey_id}) if survey: logger.info(f"Removed Survey: {survey['description']}") return
def apagar_grupo(idgrupo): """Apagar id go grupo""" logger.info("Apagando id grupo {}".format(idgrupo)) with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute("DELETE FROM grupos WHERE idgrupo=?", (idgrupo, )) conn.commit(()) cursor.close()
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 add_survey(survey): for q in survey.questions: q["results"] = {f"_{k}": None for k in get_from_all_frichtle(info="user_id")} survey["_id"] = survey["survey_id"] db.surveys.insert_one(survey.to_json()) logger.info("Saved Survey: {}".format(str(survey).replace("\n", ";"))) return
def cancel_event(event_id=None, ev=None): if event_id is None: event_id = ev.event_id event = db.events.find_one({"_id": event_id}) new_attendance = {k: (-1)*v for k, v in event["attendance"].items()} db.events.update_one({"_id": event_id}, {"$set": {"active": False, "attendance": new_attendance}}) logger.info(f"Canceled Event: {event['description']}") return
def buscar_grupos(): """Retornar os ids dos grupos salvos""" logger.info("Buscando id dos grupos salvos.") with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute("SELECT idgrupo FROM grupos") resposta = cursor.fetchall() cursor.close() if resposta: return resposta[0]
def atualizar_status(idPost): """Atualizar status do post para 1(postado) :param idPost: id do post capturado pela bloggerapi""" logger.info("Atualizando status para postado com o id: {}".format(idPost)) with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute( """UPDATE publicacoes SET publicado=1 WHERE idPost=?;""", (idPost, )) conn.commit() cursor.close()
def salvar_grupo(idgrupo): """Salvar o id do grupo na tabela grupos""" if type(idgrupo) != int: raise TypeError('Grupo id deve ser do tipo inteiro') logger.info("Salvando id grupo: {}".format(idgrupo)) with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute("""INSERT OR IGNORE INTO grupos(idgrupo) VALUES(?)""", (idgrupo, )) conn.commit() cursor.close()
def ultimo_post(limit=10): """Buscar ultimos posts adicionados no banco de dados :param limit: quantidade de posts retornados""" logger.info("Buscando ultimos posts no banco de dados.") with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM publicacoes ORDER BY id DESC limit ?;", (limit, )) resposta = cursor.fetchall() cursor.close() if resposta: return resposta
def status_postado(idPost): """Checar se o id do post foi postado :param idPost: id do post capturado pela bloggerapi""" logger.info("Verificando se foi postado com id post: {}".format(idPost)) with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute("SELECT publicado FROM publicacoes WHERE idPost=?", (idPost, )) resposta = cursor.fetchone() cursor.close() if resposta: return 1 in resposta
def create_app(): app = flask.Flask(__name__) app.register_blueprint(bot_bp) db_client = DatabaseClient.get_instance() logger.info('Removing old webhook') bot.remove_webhook() bot.set_webhook(url=WEBHOOK_URL, certificate=open(WEBHOOK_SSL_CERT, 'r')) logger.info('Successfully register new webhook') query_worker = Worker(push_message) query_worker.start() return app
def buscar_posts(): """Buscar posts no banco de dados com a data atual""" logger.info("Buscando posts no banco de dados por data.") dataHoje = time.strftime('%Y-%m-%d') with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute("SELECT * FROM publicacoes WHERE data_publicacao=?", (dataHoje, )) resposta = cursor.fetchall() cursor.close() if resposta: return resposta
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 existe_id(idPost): """Checar se o id do post existe do Banco de dados :param idPost: id do post capturado pela bloggerapi""" logger.info("Verificando se existe idpost com o id: {}".format(idPost)) with BancoDados(nomeDB) as conn: cursor = conn.cursor() cursor.execute( """ SELECT idPost FROM publicacoes WHERE idPost=?; """, (idPost, )) resposta = cursor.fetchone() cursor.close() if resposta: return idPost in resposta
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