def test_callback(call): # вывод списка кинотеатров if call.data == 'list_cinema': bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, \ text='Выберите кинотеатр:', reply_markup=parseXML.cinema_keyboard()) elif call.data == 'start_menu': bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, \ text='Выберите:', reply_markup=keyboard) # вывод списка фильмов elif call.data == 'list_films': bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, \ text='Выберите кинофильм:', reply_markup=parseXML.films_keyboard()) # выводим список киносеансов по кинотеатру elif re.search(r'cinema\d+', call.data): match = re.search(r'cinema(\d+)', call.data) split_text = util.split_string("Фильм:" + get_list_cinema_after_now(parseXML.get_films_by_cinema(match.group(1)), False), 3000) for text in split_text: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, \ text=text, parse_mode="Markdown", reply_markup=keyboard_after) # выводим список киносеансов по фильму elif re.search(r'film\d+', call.data): match = re.search(r'film(\d+)', call.data) split_text = util.split_string(get_list_cinema_after_now(parseXML.get_cinema_by_film(match.group(1)), True), 3000) for text in split_text: bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, \ text=text, parse_mode="Markdown", reply_markup=keyboard_after) # выводим ближайшие киносеансы elif call.data == 'last_sessions': split_text = util.split_string(get_list_cinema_after_now(parseXML.parse_xml()), 3000) for text in split_text: bot.send_message(call.message.chat.id, text, parse_mode="Markdown", reply_markup=keyboard_after) c_log.log_text_call(call)
def enter_text(message): text_field = message.text #pattern = re.compile(r"[a-zA-Z0-9А-Яа-я<!\[.*?\]>+-]+") pattern = re.compile(r"[a-zA-Z0-9А-Яа-я<!\[.*?\]>+-=`~]+") pattern_binar = re.compile("[0-1]+") split_message = [] mode = '' count_spaces = 0 get_regex_binar = [] if message.chat.type == 'private': if text_field == 'Beer' or text_field == 'beer' or text_field == 'пиво' or text_field == 'Пиво' or text_field == 'Пивас' or text_field == 'пивас' or text_field == 'Пивасик' or text_field == 'пивасик' or text_field == 'Пивусик' or text_field == 'пивусик': bot.send_message(message.chat.id, '> Take your beer, Sir!🍻🍺') return for i in str(text_field): if (i.isspace()) == True: count_spaces += 1 if text_field: if re.search(r'([0-1])', text_field): mode = 'btt' text_field = text_field.split() splitted_text = util.split_string(''.join(text_field), 3000) for text in splitted_text: bot.send_message(message.chat.id, text_from_bits(''.join(text))) text_field = ''.join(text_field) break else: mode = 'ttb' splitted_text = util.split_string(text_field, 200) for text in splitted_text: bot.send_message(message.chat.id, text_to_bits(''.join(text))) break now = datetime.now() current_time = now.strftime( "%Y/%m/%d;%H:%M:%S") #на 3 часа позднит по моему времени. get_first_name = str(message.from_user.first_name) get_last_name = str(message.from_user.last_name) get_username = str(message.from_user.username) if get_first_name == 'None': get_first_name = 'No first name' if get_last_name == 'None': get_last_name = 'No last name' print('LOG ->>' + current_time + ' , ' + 'User data - ' + str(get_first_name) + ':' + str(get_last_name) + ':' + str(get_username) + ' , ' + 'message_text: ' + "* " + text_field + " *" + ' , mode - ' + mode) mode = '' count = 0 else: bot.send_message(message.chat.id, '> Error! Please try again!')
def send_large_msg(chat_id, msg): ''' Markdown style (it's have a strong character limit ): to use this mode, pass Markdown in the parse_mode when using sendMesage. Use the following syntax in your message. *bolt text* _italic text_ [inline URL](http://www.google.com) [inline mention of a user](tg://user?id=123456) `inline fixed-width code` ``` block_language pre-formatted fixed-width code block ``` HTML style (has a lite character limit) <b>bolt</b> <i>italic text</i> <a href="http://www.google.com">inline URL</a> <a href="tg://user?id=123456">inline mention of a user</a> <code>inline fixed-width</code> <pre>pre-formatted fixed-width code block</pre> ''' # split into pieces incoming messtages splited_msg = util.split_string(msg, 4000) # in cycle send answer in piece for txt in splited_msg: # Parse mod HTML need for beauty output in telegram ))) try: bot.send_message(chat_id, txt, parse_mode="HTML") except: txt = txt.replace("<code>", " ") txt = txt.replace("</code>", " ") bot.send_message(chat_id, txt, parse_mode="HTML")
def to_tg_handler(sender, **kwargs): """Handle signals sent to Telegram. This will involve sending messages through the Telegram bot. Args: phone (str): Phone number that sent the message. message (str): The message received """ phone = kwargs.get('phone') message = kwargs.get('message', '') # Check if known contact contact = get_contact(phone) if not contact: # Unknown sender output = 'Message from #unknown\n' output += 'Phone number: %s\n' % phone logger.info('received message from unknown number: %s' % phone) else: # Known sender output = 'Message from #%s\n' % contact logger.info('received message from %s' % contact) output += '---------\n' output += message # Deliver message through Telegram for chunk in tgutil.split_string(output, 3000): tgbot.send_message(SETTINGS['owner'], chunk)
def total_msgs(message): usersID=[] usersName=[] username=[] combinacao = [] top=[] # txt com todos usuários usuarios = open("Usuarios.txt", "r", encoding="latin-1").readlines() # remover repetidos usuarios_unicos = list(dict.fromkeys(usuarios)) # Dividir em Nome - ID for item in usuarios: usersID.append(re.search('- (\d*)', item)[1]) usersName.append(item[:item.find('-')]) username.append(re.search('@(\w*)', item)[1]) # Combinacao é uma lista que contempla Nome-ID combinacao.extend([list(i) for i in zip(usersName, usersID, username)]) # Criar uma lista com todos usuarios correcao='' contagem=0 for b in collections.Counter(usersID).most_common(): for a in range(0,len(usersID)): #print(str(b[0]) + '-' + str(combinacao[a][1])) if str(b[0])==str(combinacao[a][1]) and correcao!=str(b[0]): #print(str(combinacao[a][0]) + ' - mensagens: '+ str(b[1])) correcao=str(b[0]) contagem = contagem+1 top.append(str(contagem) + ' : ' + str(combinacao[a][0]) + ' (@' + str(combinacao[a][2]) + ') - MSGs: '+ str(b[1])) splitted_text = util.split_string('\n'.join(top), 3000) for text in splitted_text: bot.reply_to(message,"Número de mensagens por membro: \n" + text)
def help(msg): chat_id = msg.chat.id large_text = open("help.txt", "rb").read() splitted_text = util.split_string(large_text, 3000) print(msg) for text in splitted_text: bot.send_message(chat_id, text)
def start(msg): chat_id = msg.chat.id large_text = open("start_msg.txt", "rb").read() splitted_text = util.split_string(large_text, 3000) bot.send_message(chat_id, "\xF0\x9F\x98\x81 \xF0\x9F\x91\x8B") for text in splitted_text: bot.send_message(chat_id, text)
async def listen_kafka(task_id, items, bot, message): consumer = AIOKafkaConsumer( 'data', 'finished', loop=asyncio.get_event_loop(), bootstrap_servers= '78.157.221.27:9091, 78.157.221.43:9091, 78.157.221.45:9091', value_deserializer=lambda m: json.loads(m.decode('utf8'))) await consumer.start() async for msg in consumer: if msg.topic == 'data': if msg.value.get('task_id') == task_id: item = msg.value text = '{} {}'.format( len(items) + 1, json.dumps(item, sort_keys=True, indent=4, separators=(",", ": "), ensure_ascii=False)) splitted = util.split_string(text, 3000) for text in splitted: bot.send_message(message.chat.id, text, disable_notification=True, disable_web_page_preview=True) sleep(.3) items.append(item) elif msg.topic == 'finished': if msg.value.get('task_id') == task_id: break await consumer.stop()
def echo_all(message): try: global totalcount totalcount += 1 global chatcount chatcount += 1 if message.content_type != 'text': bot.reply_to(message,'抱歉,我还只支持文字!') logging.info(str('Chat::@{} ({} {}): {}'.format(message.from_user.username, message.from_user.first_name, message.from_user.last_name, message.text))) #print(message.type) #print(type(message.from_user)) #if len(message.text) > 15: # bot.reply_to(message,'你说的内容太长了!何不切分一下试试?') # return ret = Process(message.text, 1000) if len(ret) >= 4500: bot.reply_to(message, '您要说的内容实在太长了,将为您分段处理!') splitted_ret = util.split_string(ret, 3000) logging.info(str('Too long.Split into '+str(len(splitted_ret))+' parts')) for sret in splitted_ret: bot.reply_to(message, sret) #sleep(0.3) else: bot.reply_to(message,ret) except Exception as e: rid = getReportID() traceback.print_exc() logging.error(str(rid + '::' + str(repr(e)) + '\n' + traceback.format_exc())) bot.send_message(message.from_user.id,'抱歉,我出现错误,识别ID为 '+rid+'\n\n信息如下:\n'+str(repr(e))+'\n\n请将这条信息 Forward 给 @abc1763613206 中所列的用户 进行处理!')
def CMD(command): try: shell = re.split('/CMD ', command.text, flags=re.I)[1] bot.send_chat_action(command.chat.id, 'typing') cmd = subprocess.Popen(shell, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) lines = [] for line in cmd.stdout.readlines(): line = line.strip() if line: lines.append(line.decode('cp866')) Output = '\n'.join(lines) bot.send_message(command.chat.id, Output) except: try: shell = re.split('/CMD ', command.text, flags=re.I)[1] splitted_text = util.split_string(Output, 4096) for Output in splitted_text: bot.send_message(command.chat.id, Output) except UnboundLocalError: bot.reply_to(command, '*Empty Line*', parse_mode='Markdown') except: bot.send_message(command.chat.id, '*Enter Command\n\n› /CMD*', parse_mode='Markdown')
def send_poem(message, link): poem = sql_cmd( "SELECT name, body FROM asadov WHERE link = '{}'".format(link)) if poem: name = poem[0][0] body = poem[0][1] keyboard = telebot.types.InlineKeyboardMarkup() plus_fav_button = telebot.types.InlineKeyboardButton( text=plus_smile + star_smile, callback_data="add::" + link) minus_fav_button = telebot.types.InlineKeyboardButton( text=minus_smile + star_smile, callback_data="remove::" + link) show_fav_button = telebot.types.InlineKeyboardButton( text=magnifying_smile + star_smile, callback_data="show") keyboard.add(plus_fav_button, minus_fav_button, show_fav_button) if len(body) > 4000: splited_text = util.split_string(body, 4000) count = len(splited_text) bot.send_message(message.chat.id, name + '\n') for large_text in splited_text: if large_text == splited_text[count - 1]: bot.send_message(message.chat.id, large_text, reply_markup=keyboard) else: bot.send_message(message.chat.id, large_text) else: bot.send_message(message.chat.id, name + '\n' + body, reply_markup=keyboard) else: bot.send_message(message.chat.id, "Ошибочная ссылка")
def ls(command): try: bot.send_chat_action(command.chat.id, 'typing') dirs = '\n``'.join(os.listdir()) bot.send_message(command.chat.id, '`' + os.getcwd() + '`\n\n' + '`' + dirs + '`', parse_mode='Markdown') except: try: dirse = '\n'.join(os.listdir()) splitted_text = util.split_string(dirse, 4096) for dirse in splitted_text: bot.send_message(command.chat.id, '`' + dirse + '`', parse_mode='Markdown') except PermissionError: bot.send_message(command.chat.id, '*Permission Denied!*', parse_mode='Markdown') except: pass
def handle_subreddit_choosen(callback_query): message = callback_query.message subreddit_name = callback_query.data post_list = redditApi.get_last_posts_from_subreddit(subreddit_name) for item in post_list: date = datetime.datetime.fromtimestamp(int(item["created"])) date = date.strftime('%d-%m-%Y %H:%M:%S') # result_message = "<b>{}</b>\n".format(item["title"]) result_message = "" url = get_gif_url_from_item_url(item["url"]) if url and (url.endswith(".gif") or url.endswith(".mp4")): result_message += "<a href='{}'>{}</a>".format( url, "View on Reddit") result_message += " {}\n".format(date) # result_message += "{}\n".format(item["text"]) if len(result_message) > 4000: splitted_text = util.split_string(result_message, 4000) for text in splitted_text: bot.send_message(message.chat.id, text, False, parse_mode="HTML") else: bot.send_message(message.chat.id, result_message, False, parse_mode="HTML") time.sleep(1)
def mentionOneText(bot, message): if message.chat.type != 'private': listUsers = botFunctions.mentionedList(message.chat.id, message.text) if message.reply_to_message is not None and not message.reply_to_message.from_user.is_bot and botFunctions.memberInTheGroup(bot, message.chat.id, message.reply_to_message.from_user.id): listUsers.append(str(message.reply_to_message.from_user.id)) listUsers = list(set(listUsers)) listSUB = re.split('\W+', message.text) listSUB = list(set(listSUB)) if len(listUsers) > 0: mentionedUser = botFunctions.getName(message.from_user) for uname in listUsers: if botFunctions.memberInTheGroup(bot, message.chat.id, uname) and str(message.from_user.id) != uname: content = message.text for subName in botFunctions.getSubscribeName(uname): for sname in listSUB: if sname.lower() == subName.lower(): for i in range(content.count(sname)): botFunctions.updateSubscribeNameCount(sname, uname) p = re.compile(r"\b{0}\b".format(sname)) content = p.sub("<b>" + sname + "</b>", content) text = mentionedUser + ' @ <b>' + message.chat.title + '</b> : ' + content try: splitted_text = util.split_string(text, 3000) for text in splitted_text: bot.send_message(chat_id=uname, text=text, parse_mode='HTML') except: print('single mention/subscribe failed') if message.reply_to_message is not None and str(message.reply_to_message.from_user.id) != uname: try: bot.forward_message(chat_id=uname, from_chat_id=message.chat.id, message_id=message.reply_to_message.message_id) except: print('single mention/subscribe forward failed')
def sendtg(self, parser): """ Send a message to an user through Telegram. In order to do this, the agent will `guess` who the recipient is based on the `to` tag in the parser. """ to = self.guess(parser.get('to')) if not to: # Did not find unique ID print('Cannot find Telegram ID for %s' % parser.get('to')) return msg = parser.get('msg') if msg: # API supports a maximum of 5000 characters per message # This will divide the messages in chunks of 3000 characters text_chunks = util.split_string(msg, 3000) for chunk in text_chunks: # self.bot.send_message(to, chunk, parse_mode='Markdown') self.bot.send_message(to, chunk) voice = parser.get("voice") if voice: f = "/tmp/" + parser.get('to') + ".wav" subprocess.call(["pico2wave", "-l", "es-ES", "-w", f, voice]) v = open(f, 'rb') self.bot.send_voice(to, v) v.close() img = parser.get("img") if img: v = open(img, 'rb') self.bot.send_photo(to, v) v.close()
def CMD(command): try: Command = re.split('/CMD ', command.text, flags=re.I)[1] CMD = Popen(Command, shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE) Lines = [] for Line in CMD.stdout.readlines(): Line = Line.strip() if Line: Lines.append(Line.decode('cp866')) Output = '\n'.join(Lines) bot.send_message(command.chat.id, Output) except: try: Command = re.split('/CMD ', command.text, flags=re.I)[1] SplittedText = util.split_string(Output, 4096) for Output in SplittedText: bot.send_message(command.chat.id, Output) except UnboundLocalError: bot.reply_to(command, '_Command completed!_', parse_mode='Markdown') except: bot.send_message(command.chat.id, '_Enter your command_\n\n*› /CMD*', parse_mode='Markdown')
def getting_text(message): cid = message.chat.id global text global have_text global have_level text = message.text have_text = True if have_level == False: markup = types.ReplyKeyboardMarkup() itembtna1 = types.KeyboardButton('A1') itembtna2 = types.KeyboardButton('A2') itembtnb1 = types.KeyboardButton('B1') itembtnb2 = types.KeyboardButton('B2') itembtnc1 = types.KeyboardButton('C1') itembtnc2 = types.KeyboardButton('C2') markup.row(itembtna1, itembtna2, itembtnb1) markup.row(itembtnb2, itembtnc1, itembtnc2) bot.reply_to(message, "Теперь выберите свой уровень:", reply_markup=markup) else: hideboard = types.ReplyKeyboardRemove() bot.reply_to(message, 'Список слов, которые вы можете не знать:', reply_markup=hideboard) large_text = return_words(text, level) splitted_text = util.split_string(large_text, 3000) for message_text in splitted_text: bot.send_message(cid, message_text) have_text = False have_level = False
def definicao_informal(message): # Receber a palavra a ser definida manip_string = message.text definicao = manip_string[manip_string.find(' ')+1:] print(definicao) #definicao = re.findall('Defina (\w*)', message.text)[0] try: # Codigo-fonte dicionario informal link = "https://www.dicionarioinformal.com.br/" + str(definicao) response = requests.get(link) html = response.text soup = BeautifulSoup(html, "html.parser") # Caso não encontre a definição - mistyping codigo = soup.find('div', {'class': 'col-xs-12 col-sm-6'}) if str(codigo.text.strip()) == 'Nenhuma Definição encontrada.': erro = soup.find('div', {'class': 'di-blue-link'}) print(erro) bot.reply_to(message, "Você não quis dizer: \n" + str(erro.text.strip())) # Caso encontre a definição else: bot.reply_to(message, str(soup.find('p', {'class': 'text-justify'}).text.strip())+'\n\n'+'Exemplo: ' + str(soup.find('blockquote', {'class': 'text-justify'}).text.strip())) except telebot.apihelper.ApiException: splitted_text = util.split_string(str(soup.find('p', {'class': 'text-justify'}).text.strip())+'\n\n'+'Exemplo: ' + str(soup.find('blockquote', {'class': 'text-justify'}).text.strip()), 3000) for text in splitted_text: bot.reply_to(message, text) except AttributeError: bot.reply_to(message, "Definição não encontrada")
def pysearch(message): argument = get_arg(message.text) if argument == '' or argument is None: return response = list_packages(argument) splitted_text = util.split_string(response, 3000) for text in splitted_text: bot.reply_to(message, text)
def send_telegram_message(token: str, chat_id: int, message: str) -> Result[bool]: try: bot = TeleBot(token) for text in split_string(message, 4096): bot.send_message(chat_id, text) return Result(ok=True) except Exception as e: return Result(error=str(e))
def pysearch(message): argument = get_arg(message.text) if argument == '' or argument == None: return response = list_packages(argument) splitted_text = util.split_string(response, 3000) for text in splitted_text: bot.reply_to(message,text)
def pretty_send(chat_id, delimeter): if len(delimeter.join(chats[chat_id]['group_list'])) <= 3000: bot.send_message(chat_id, delimeter.join(chats[chat_id]['group_list'])) else: splitted = util.split_string( delimeter.join(chats[chat_id]['group_list']), 3000) for text in splitted: bot.send_message(chat_id, text) del chats[chat_id]
def split_long_text(text): split_text = util.split_string(text, 3000) res = [] for i, n in enumerate(split_text): if not n.endswith('\n'): n += split_text[i + 1][:split_text[i + 1].find('\n') + 1] split_text[i + 1] = split_text[i + 1][split_text[i + 1].find('\n') + 1:] res.append(n) return res
def _send_telegram_message(self, message: str): try: bot = TeleBot(self.get_bot().telegram_token) chat_id = self.get_bot().telegram_channel_id for text in split_string(message, 4096): bot.send_message(chat_id, text) except Exception as e: self.log.error(f"send_telegram_message: {str(e)}") return str(e)
def botLog(bot, message): try: splitted_text = util.split_string(botFunctions.changeLOG(), 3000) for text in splitted_text: bot.send_message(chat_id=message.chat.id, text=text, parse_mode='HTML') except: print('botLog seding failed')
def smallInfo(mes): set_lang(mes.chat.id) get = del_comand('info', mes) try: summary = wikipedia.summary(get) except: summary = "not found" spliter_summary = util.split_string(summary, 3000) for text in spliter_summary: bot.send_message(mes.chat.id, text)
def send_answer(message): method = ChooseMethods(message.text) Route(method.kwargs) large_text = open('data.txt', 'rb').read() splitted_text = util.split_string(large_text, 3000) for text in splitted_text: bot.send_message(message.chat.id, text) file = open('data.txt', 'rb') bot.send_document(message.chat.id, file) file.close()
def show_my_messages(message): result = posts.find({'user-id': message.from_user.id}) message_text = '' for post in result: message_text += f"Date = {post['datetime']} \n" message_text += f"Text = {post['text']} \n" message_text += '\n' splitted_text = util.split_string(message_text, 3000) for text in splitted_text: bot.send_message(message.from_user.id, text)
def feedback(self, parser): """Send the feedback of a command through Telegram.""" tgchat = int(parser.get('tgchat')) text = parser.get('feedback-string') # API supports a maximum of 5000 characters per message # This will divide the messages in chunks of 3000 characters text_chunks = util.split_string(text, 3000) for chunk in text_chunks: # self.bot.send_message(tgchat, chunk, parse_mode='Markdown') self.bot.send_message(tgchat, chunk)
def privateText(bot, message): hhhFunc(bot, message) if message.from_user.id == admin and message.reply_to_message is not None: try: splitted_text = util.split_string(message.text, 3000) for text in splitted_text: bot.send_message(chat_id=message.reply_to_message.forward_from.id, text=text, parse_mode='HTML') except: print('Cannot send message to pm user') return if message.from_user.id != admin: bot.forward_message(chat_id=admin, from_chat_id=message.chat.id, message_id=message.message_id)
def handle_text(message): if message.chat.type == "private" and message.from_user.id in superadmins: warnings = db.all_warnings() text = "All warnings:\n\n" for warning in warnings: if str(warning[0]) == 'none': pass else: text += "<b>@%s</b>: %s\n" % (str(warning[0]), str(warning[1])) splitted_text = util.split_string(text, 3000) for text in splitted_text: bot.send_message(message.chat.id, text, parse_mode='HTML')
def sendMessage(message, chat_id): with tempfile.NamedTemporaryFile() as temp: try: temp.write(message) temp.flush() temp.seek(0) doc = open(temp.name, 'rb').read() splitted_text = util.split_string(doc, 3000) for text in splitted_text: bot.send_message(chat_id, text) except Exception as e: print e finally: temp.close()
def encode(message): string=message.text key = Fernet.generate_key() cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt(string.encode(encoding='UTF-8')) bot.send_message(message.chat.id,"Questo è il tuo messaggio criptato: ") try: bot.send_message(message.chat.id,cipher_text.decode(encoding='UTF-8')) except Exception as e: if "400" in str(e): splitted_text=util.split_string(cipher_text.decode(encoding='UTF-8'),3000) for text in splitted_text: bot.send_message(message.chat.id,text) else: print(str(e)+" in funzione encode") bot.send_message(message.chat.id,"Questa è la tua chiave crittografica") bot.send_message(message.chat.id,key)
def sendtg(self, parser): """Send a message to an user through Telegram. In order to do this, the agent will `guess` who the recipient is based on the `to` tag in the parser. """ to = self.guess(parser.get('to')) if not to: # Did not find unique ID print('Cannot find Telegram ID for %s' % parser.get('to')) return # Text messages msg = parser.get('msg') if msg: # API supports a maximum of 5000 characters per message # This will divide the messages in chunks of 3000 characters text_chunks = util.split_string(msg, 3000) for chunk in text_chunks: # self.bot.send_message(to, chunk, parse_mode='Markdown') self.bot.send_message(to, chunk) # Voice messages voice = parser.get('voice') if voice: wavpath = path('/tmp', parser.get('to') + '.wav') # Use pico TTS #TODO check language subprocess.call(['pico2wave', '-l', '-w', wavpath, voice]) with open(wavpath, 'rb') as f: self.bot.send_voice(to, f) # Files/Attachments att = parser.get('att') if att: with open(att, 'rb') as f: self.bot.send_document(to, f) # Images img = parser.get('img') if img: with open(img, 'rb') as f: self.bot.send_photo(to, f)
def decripta_messaggio(message): try: key = message.text user = user_dict[message.chat.id] user.key = key plain_text=Fernet(user.key.encode(encoding='UTF-8')).decrypt(user.encmessage.encode(encoding='UTF-8')) bot.send_message(message.chat.id,"Il messaggio decriptato è il seguente:") try: bot.send_message(message.chat.id,plain_text.decode(encoding='UTF-8')) except Exception as e: if "400" in str(e): splitted_text=util.split_string(plain_text.decode(encoding='UTF-8')) for text in splitted_text: bot.send_message(message.chat.id,text) else: print(str(e)+" in funzione decripta_messaggio") except Exception as e: risposta(message,'Si è verificato un errore, sicuro di aver copiato bene il messaggio?') print(str(e)+" in funzione decripta_messaggio")
def handle(msg): chat_id = msg['chat']['id'] content_type, chat_type,chat_id = telepot.glance(msg) print(content_type,chat_type,chat_id) if content_type == 'text': command = msg ['text'] print ('Got command: %s' % command) if command == '/roll': texto = random.randint(1,20) elif command == '/time': dia = getTime('dia') hora = getTime('horaMinSec') texto = emoji.emojize(':date:', use_aliases = True)+ dia + '\n'+emoji.emojize(':alarm_clock:', use_aliases = True) + hora elif command == '/clima': #yahoo_result = pywapi.get_weather_from_yahoo('ARCS0025') #los de yahoo no estaban andando por eso utilizo el weather.com #estado = string.lower(yahoo_result['condition']['text']) #grado = yahoo_result['condition'] ['temp'] + "°C" weather_com_result = pywapi.get_weather_from_weather_com('ARCS0025') #Este es Weather.com estado = string.lower(weather_com_result['current_conditions']['text']) grado = weather_com_result['current_conditions']['temperature'] hora = int(getTime('hora')) print estado if estado == 'cloudy': emoticon = "Nublado " + emoji.emojize(':cloud:', use_aliases = True) elif estado == 'mostly cloudy': emoticon = "Muy Nublado " + emoji.emojize(':cloud:', use_aliases = True)+" "+ emoji.emojize(':cloud:', use_aliases = True)+" "+ emoji.emojize(':cloud:', use_aliases = True) elif estado=='fair': if hora>=7 and hora <= 19: emoticon = "Adorable " + emoji.emojize(':sunny:', use_aliases = True) else: emoticon = "Adorable" + emoji.emojize(':first_quarter_moon_with_face:', use_aliases = True) texto = "El clima en Corrientes es: " + emoticon + " con " + grado + "C" elif command == 'Hola' or command == 'hola': name = msg['chat']['first_name'] emoticon = emoji.emojize(':wave:', use_aliases = True) texto = "Hola " + name +emoticon+"\nEnvia /help para ver los comandos." elif command == '/help': texto = '/time - Hora y Fecha del Sistema \n/clima - Pronostico de Corrientes \n/info - Acerca de...' elif command == "OnTv" or command == "OffTv": ardon("on") if command == "OnTv": bot.sendMessage(chat_id, "Espere que se esta encendiendo la TV") time.sleep(10) texto = "Se encendio la TV" else: texto = "Se apago la TV" elif command == "Musica1": ardOn("musica") texto = "Se Cambio al canal de musica" elif command == "Fox": ardOn("fox") texto = "Se ha cambiado al canal Fox" elif command == "Disney": ardOn("disney") texto = "Se ha cambiado al canal Disney Junior" elif command == "TvVol+": ardOn("vol+") texto = "Se subio 10 unidades de Volumen" elif command == "TvVol-": ardOn("vol-") texto = "Se bajo 10 unidades de Volumen" elif "Canal " in command: try: canal = int(command[6:8]) print canal ardOn(canal) texto = "Cambiado al canal "+ str(canal) except ValueError: texto = "Error no existe ese canal" elif "Buscar " in command: totChar = len(command) + 1 bus = command[7:totChar] wikipedia.set_lang("es") try: texto = wikipedia.summary(bus) splitted_text = util.split_string(texto,3000) for text in splitted_text: bot.sendMessage(chat_id,text) texto = "OK" except wikipedia.exceptions.PageError : texto = "Error, pruebe con otro nombre." else: texto = "Disculpa no conozco ese mensaje." bot.sendMessage(chat_id, texto) elif content_type=='photo': dir = str(datetime.datetime.now())+'.png' bot.download_file(msg['photo'][-1]['file_id'], '/home/pi/Desktop/repositorio/Imagenes/%s' % dir)
def help(bot, msg): chat_id = msg.message.chat.id large_text = open(help_msg, "rb").read() splitted_text = util.split_string(large_text, 3000) for text in splitted_text: bot.sendMessage(chat_id, text)