def run_bot(): MessageLoop(bot, {'chat':handler, 'callback_query':daily_feedback1}).run_as_thread() while 1: time.sleep(10)
# Formats bus-arrival-time message bot.sendMessage( from_id, '<b>ESTIMATED ARRIVAL TIME</b>\n' 'Here are the estimated bus arrival times\nfor bus ' + serviceNo + ': \n\n' '🚌 First Bus \t\t: ' + getTime.stringTime(completeTime[0]) + '\t--\t' + str(infoList[1]) + "\n" '🚌 Second Bus \t\t: ' + getTime.stringTime(completeTime[1]) + '\t--\t' + str(infoList[2]) + "\n" '🚌 Third Bus \t: ' + getTime.stringTime(completeTime[2]) + '\t--\t' + str(infoList[3]) + "\n\n" 'Operator \t\t:\t' + str(infoList[0]) + '\n\n' '👍👍 HAVE A NICE TRAVEL 👍👍', 'HTML') #Hard-code our token into the program TOKEN = '471247568:AAFxc95gec9U0QNi0MYPKppZY548JRSDObE' #Runs the bot via the API bot = telepot.Bot(TOKEN) MessageLoop(bot, { 'chat': on_chat_message, 'callback_query': on_callback_query }).run_as_thread() print('Listening ...') # Keep the program running while 1: time.sleep(10)
dispatcher.dispatch(self, msg) # except Exception: # with open("errlog.txt","a") as f: # f.write(Exception.__str__() + '\n') def on_close(self, msg): # try: if self.existed_before: query = update_state.format(self.state.value, self.chat_id) else: query = insert_state.format(self.chat_id, self.first_name, self.state.value) self.query.execute(query) self.connection.commit() print("Timed out connection at state: " + str(self.state.value)) # except Exception: # with open("errlog.txt","a", encoding="urf-8") as f: # f.write(Exception.__str__() + '\n') if __name__ == '__main__': print(len(admin_chat_id)) for chat_id in admin_chat_id: notification_activate[chat_id] = False bot = telepot.DelegatorBot(TOKEN, [ include_callback_query_chat_id( pave_event_space())( per_chat_id(), create_open, StateHandler, timeout=120), ]) MessageLoop(bot).run_forever()
KEYS.remove(key_3) key_4 = random.choice(KEYS) bot.sendMessage( chat_id, ("a cosa corrisponde %s ?" % (d)), reply_markup=ReplyKeyboardMarkup( keyboard=[[ KeyboardButton(text=self.morse[key_1]), KeyboardButton(text=self.morse[key_2]) ], [ KeyboardButton(text=self.morse[key_3]), KeyboardButton(text=self.morse[key_4]) ]], resize_keyboard=True, one_time_keyboard=False)) print(self.ris[0]) TOKEN = 'INSERIRE_TOKEN_QUI' bot = telepot.DelegatorBot(TOKEN, [ pave_event_space()(per_chat_id(), create_open, MorseQuiz, timeout=3600), ]) MessageLoop(bot).run_as_thread() print(".. -. .- - - . ... .-") #in attesa while 1: sleep(60)
import time import telepot from telepot.loop import MessageLoop from Database import Database from controllers.parse_message import parse_handler # Initial setup paybot = telepot.Bot("452146569:AAH0sXMgA9rtZe7j83L6RqqLU0qbo0sY12w") paybot.getUpdates(offset=100) # Initialse Database db = Database() db.migrate() def receiver(msg): content_type, chat_type, chat_id = telepot.glance(msg) if content_type == 'text': parse_handler(chat_id, msg["chat"]["username"], msg['text']) # Run loop MessageLoop(paybot, receiver).run_as_thread() while 1: time.sleep(100)
print(content_type, chat_type, chat_id_console) if content_type == 'text' and chat_type == 'private': try: answer_to_start() except (KeyError, IndexError): print('tried to run answer_to_start!') try: answer_to_dir() except NameError: print('tried to get DIR!') try: img_poster() except NameError: print('tried to get img_poster!') try: other_messages() except NameError: pass elif content_type == 'text' and chat_type == 'channel': try: get_channel_id() except (KeyError, IndexError): print('tried to get channel_id!') MessageLoop(PosterBot, handler).run_as_thread() print('Listening ...') while 1: sleep(10)
def listen(self, handler): MessageLoop(self.bot, handler).run_as_thread()
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) faces = classifier.detectMultiScale(gray, 1.3, 5) count = 0 for (x, y, w, h) in faces: count = count + 1 cv.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5) return image, count def handle(msg): # pprint.pprint(msg) if msg["photo"]: chat_id = msg['chat']['id'] f = tempfile.NamedTemporaryFile(delete=True).name + ".png" photo = msg['photo'][-1]["file_id"] path = bot.getFile(photo)["file_path"] # bot.sendMessage(chat_id, "Retrieving %s" % path) bot.download_file(photo, f) p = cv.imread(f) hsv, l = detect(p) cv.imwrite(f, hsv) bot.sendMessage(chat_id, "found %i faces" % l) bot.sendPhoto(chat_id, open(f, 'rb')) # print("photo sent") else: print("no photo") bot = telepot.Bot(os.environ["BOT_TOKEN"]) MessageLoop(bot, handle).run_forever()
chat_id = message["message"]["chat"]["id"] message_text = json.loads(message["data"])['name'] else: chat_id = message["chat"]["id"] bot.sendMessage(chat_id, MESSAGE_ERROR) return if state == 'normal': if message_text == "/start": bot.sendMessage(chat_id, MESSAGE_START, reply_markup=KEYBOARD_START) if message_text == 'menu': bot.sendMessage(chat_id, MESSAGE_MENU, reply_markup=KEYBOARD_MENU) if message_text == 'categories': bot.sendMessage(chat_id, MESSAGE_CATEGORIES, reply_markup=get_categories_menu()) if message_text == 'add_category': state = 'add_category' bot.sendMessage(chat_id, MESSAGE_ADD_CATEGORY) if message_text == 'get_category': category = json.loads(message["data"])['data'] bot.sendMessage(chat_id, category['name'], reply_markup=get_category_menu(category['id'])) elif state == 'add_category': state = 'normal' text = add_category(message_text) bot.sendMessage(chat_id, text, reply_markup=get_categories_menu()) # цикл приема сообщений loop = asyncio.get_event_loop() loop.create_task(MessageLoop(bot, handle).run_forever()) loop.run_forever()
elif content_type == 'photo': baixarFotos(bot, msg, chat_id, FLAG) FLAG = None if FLAG is not None else FLAG else: bot.sendMessage(chat_id, 'Você não tem autorização!!!') bot.sendMessage(chat_id, """ Caso queira testar, envie uma menssagem para @ColdMaster - Menino do designer e Banco de dados. @Renanzx - Ué, Isso não vai funcionar, talvez funcione. @lucasnasm - Read the docs Orgulhosamente em fase beta!!! """, parse_mode='Markdown') if __name__ == "__main__": verifica_db() verifica_pastas() MessageLoop(bot, corpo).run_as_thread() print 'Rodando...' while 1: try: time.sleep(10) except KeyboardInterrupt: fecha_conexao() exit(0)
id=res, title=res, input_message_content=InputTextMessageContent( message_text=res))) return articles answerer.answer(msg, compute) def on_chosen_inline_result(msg): result_id, from_id, query_string = telepot.glance( msg, flavor='chosen_inline_result') print('Chosen Inline Result:', result_id, from_id, query_string) bot = telepot.Bot(private.token) answerer = telepot.helper.Answerer(bot) MessageLoop( bot, { 'chat': on_chat_message, 'inline_query': on_inline_query, 'chosen_inline_result': on_chosen_inline_result }).run_as_thread() print 'I am listening ...' while 1: time.sleep(10)
# /ac <username> <task_number> elif command[:2] == "ac": data = command[2:].split() userteam = self[data[0][1:]]["team"] if username in admins_list: if data[1] in team[userteam]: if team[userteam][data[1]] == True: bot.sendMessage(header[2], "You have accepted.") else: team[userteam][data[1]] = True team[userteam]["total"] += task[data[1]]['score'] bot.sendMessage( header[2], "Congratulations! team " + userteam + " send the correct answer!") else: team[userteam][data[1]] = True team[userteam]["total"] += task[data[1]]['score'] bot.sendMessage( header[2], "Congratulations! team " + str(userteam) + " send the correct answer!") MessageLoop( bot, { 'chat': on_chat, #'callback_query': on_callback_query, }).run_as_thread() print('Listening ...')
def onCallbackQuery(msg): # Função de ação do botão de baixar queryID, chatid, queryData = glance(msg, flavor='callback_query') bot.answerCallbackQuery(queryID, text='Seu arquivo MP3 está sendo preparado') Util.baixarMP3(resultado[int(queryData)]) bot.sendMessage( chatid, emojize('Sua música já está sendo enviada... :headphones:', use_aliases=True)) bot.sendChatAction(chatid, 'upload_audio') arq = Util.pegaMP3() bot.sendAudio( chatid, open(arq, 'rb'), title=arq[:len(arq) - 16]) # manda a música com apenas seu nome original sem url sleep(5) from os import remove remove(arq) print(f'Baixar {arq[:len(arq) - 16]}') # Nome do áudio baixado para o log MessageLoop(bot, { 'chat': onChatMessage, 'callback_query': onCallbackQuery }).run_as_thread() print(bot.getMe()) print('Escutando ...') while True: pass
categoriesdb = CategoriesDB.CategoriesDB() mediavotedb = MediaVoteDB.MediaVoteDB() # clean up mess for category in categoriesdb.getValues(): if category.creator not in usersdb.database.keys(): print("found stray category") log.info("Loaded databases") try: response = { 'chat': handle, 'callback_query': query, 'inline_query': inline_query, 'chosen_inline_result': chosen_inline } MessageLoop(bot, response).run_as_thread() except Exception as e: log.exception("main: Big mistake") log.info("Message loop started") routine = Routine.Routine() routine.run_routine_func(usersdb, mediavotedb, categoriesdb) log.info("Routine started") while 1: time.sleep(10)
def start(self): signal.signal(signal.SIGINT, self.sigint_handler) MessageLoop(self.bot, {'chat': self.handle_message, 'callback_query': self.handle_callback}).run_as_thread() while 1: time.sleep(0.007)
print(" status:", user.status) print(" question:", user.question) # 聊天種類 print("😎 CHAT") print(" type:", msg['chat']['type']) if msg['chat']['type'] != 'private': print(" title:", msg['chat']['title']) # 使用者傳送文字 if 'text' in msg: print("😯 TEXT") print(" text:", msg['text']) if 'caption' in msg: print("😯 TEXT") print(" text: ", msg['caption']) # 使用者傳送檔案 if 'document' in msg: print("😠 DOCUMENT") print(" file_name:", msg['document']['file_name']) print(" file_id:", msg['document']['file_id']) # 開始執行 MessageLoop(bot, on_chat).run_as_thread() print("Started! Service is available.") while True: time.sleep(60) # 定期敲 Telegram 讓 Bot 不要死掉 bot.getMe()
def IQ_find_user_ind(self, username): for i in range(len(self.infa_queue)): if self.infa_queue[i] == username: return i return -1 def IQ_delete_user(self, username): del self.infa_queue[self.IQ_find_user_ind(username)] def insertSession(ssn): global __SESSIONS__ __SESSIONS__.append(ssn) def findSessionByID(session_id): global __SESSIONS__ for i in range(len(__SESSIONS__)): if (__SESSIONS__[i].chat_id == session_id): return __SESSIONS__[i] return session('null', -1) random.seed(time.time()) JustBot = tp.Bot(__TOKEN__) MessageLoop(JustBot, handle).run_as_thread() print("JustBot started") while 1: time.sleep(10)
def main(): import os import sys sys.path.append(os.path.dirname(os.path.abspath( os.path.dirname(__file__)))) import datetime from datetime import timedelta import time import telepot from telepot.loop import MessageLoop from src import hourly_for_telegram # import loggingmod import traceback def start_msg(): return ''' 지역별 날씨를 예보합니다. 지역을 입력해주세요. 마침표 하나만 입력해서 이전 지역을 다시 사용할 수 있습니다. /help 로 도움말을 볼 수 있습니다. Bot command list: /start /help /command /about ''' def help_msg(): return ''' 지역별 날씨를 예보합니다. 지역을 입력해주세요. 마침표 하나만 입력해서 이전 지역을 다시 사용할 수 있습니다. Bot command list: /start /help /command /about ''' def about_msg(): return ''' Hourly Weather Bot @telnturtle || [email protected] ''' def send_msg(bot, chat_id, msg): bot.sendMessage(chat_id, msg) # loggingmod.logger.info('chat_id: %s\nGMT : %s\nKST : %s\npayload: %s\n' % ( # chat_id, # datetime.datetime.now().isoformat(' ')[:19], # (datetime.datetime.now() + timedelta(hours=9)).isoformat(' ')[:19], # msg)) print('chat_id: %s\nGMT : %s\nKST : %s\npayload: %s\n' % (chat_id, datetime.datetime.now().isoformat(' ')[:19], (datetime.datetime.now() + timedelta(hours=9)).isoformat(' ')[:19], msg)) def handle(msg_): content_type, chat_type, chat_id = telepot.glance(msg_) time_diff = time.time() - msg_['date'] time_diff_limit = 60 text = msg_['text'] if content_type == 'text' and text.startswith('/'): if text == '/start': send_msg(bot, chat_id, start_msg()) elif text == '/help': send_msg(bot, chat_id, help_msg()) elif text == '/about': send_msg(bot, chat_id, about_msg()) if content_type == 'text' and time_diff_limit > time_diff and not text.startswith( '/'): # 'Sorry, an error occurred. Please try again later.' NO_RESULT_MSG = '일치하는 검색결과가 없습니다.' payload_list = [] try: payload_list = hourly_for_telegram.make_payload(chat_id, text, aq=True, daily=True) # for weather.com only # payload_list[0] = (payload_list[0].replace('Rain', 'Rain☔') # .replace('Thunderstorm', 'Thunderstorm⛈') # .replace('Cloudy', 'Cloudy☁️') # .replace('Clouds', 'Clouds☁️') # .replace('Clear', 'Clear☀️') # .replace('Overcast', 'Overcast☁️')) except Exception as e: payload_list.insert(0, NO_RESULT_MSG) # loggingmod.logger.error(e, exc_info=True) traceback.print_exc() send_msg(bot, chat_id, payload_list[0]) for msg_ in payload_list[ 1:] if payload_list[0] != NO_RESULT_MSG else []: send_msg(bot, chat_id, msg_) with open( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'rsc', '_keys', 'keys'), 'r') as f: TOKEN = f.readlines()[9][:-1] bot = telepot.Bot(TOKEN) _count = 5 while 1: try: MessageLoop(bot, handle).run_as_thread(allowed_updates='message') # loggingmod.logger.info('Listening ...') print('Listening ...') while 1: time.sleep(5) except Exception as e: # loggingmod.logger.error(e, exc_info=True) traceback.print_exc() _count = _count - 1 if _count < 1: break # Keep the program running. while 1: time.sleep(10)
def __init__(self, token, log): self.bot = telepot.Bot(token) MessageLoop(self.bot, self.handle).run_as_thread() log.info("Listening for Filters configurations")
def setTalkHandleFunction(self, handle): MessageLoop(self.wrBot, handle).run_as_thread()
def __init__(self): MessageLoop(bot, self.bot_hadler).run_as_thread() print('[*] Bot connected') while True: time.sleep(10)
else: reply = 'Can\'t find answer to your response' bot.sendMessage(user_id, reply) elif len(Message_list.intersection(sending_picture))>1: bot.sendPhoto(user_id, photo=open('picture.png', 'rb')) elif len(Message_list.intersection(sending_audio))>1: bot.sendAudio(user_id, audio = open('fracture.mp3', 'rb')) elif len(Message_list.intersection(sending_video))>1: bot.sendVideo(user_id, video = open('cars.mp4', 'rb')) elif len(Message_list.intersection(sending_document))>1: bot.sendDocument(user_id, document =open('knowledge.json', 'rb')) else: reply = 'Sorry didn\'t understand it \n can you rephrase it in another short way' bot.sendMessage(user_id, reply) def sending_message(): for user in active_user_id: quote = random_quote() bot.sendMessage(user, quote) MessageLoop(bot, check_new).run_as_thread() while True: time.sleep(10) sending_message()
bot.sendMessage(chat_id,message) #Viene confermato o meno che il messaggio è stato inviato else: #Messaggio da un utente if command == "/start": #Messaggio di benvenuto message = """Benvenuto nel mio bot limitati.\nManda un messaggio per iniziare la conversazione. Ti risponderò appena posso.\nPuoi usare /license per informazioni sulla licenza.""" bot.sendMessage(chat_id,message) elif command == "/license": #Informazioni sulla licenza e su dove scaricare una copia del sorgente message = "Distribuito sotto licenza [Affero GPL](https://www.gnu.org/licenses/)." tastiera = InlineKeyboardMarkup(inline_keyboard=( [[InlineKeyboardButton(text='Source code',url=repository)]])) bot.sendMessage(chat_id,message,'Markdown',disable_web_page_preview=True,reply_markup=tastiera) try: bot.forwardMessage(amministratore,chat_id,msg['message_id']) #Inoltra il messaggio all'amministratore del bot except Exception as e: if str(e) == "'message_id'": None #È stata premuta una tastiera; non ha messaggi da inoltrare #Definire qui cosa succede quando viene premuta una tastiera, se si desidera aggiungerne else: raise #Errore sconosciuto. Viene gestito come previsto da filtro(msg) file = open(arcbanned,'wb') #Aggiorna la lista degli utenti bannati pickle.dump(banned,file) file.close() antiflood = {} bot = telepot.Bot(token) MessageLoop(bot,filtro).run_as_thread() #Riceve i messaggi while 1: antiflood = {} #Resetta il filtro antiflood ogni 5 secondi time.sleep(5)
elif command_tokens[0] in ('/help', '/help@sybilforkbot'): self.sender.sendMessage( "All commands are prefixed by a forward slash (/), with no spaces between the" + " slash and your command. Dealt cards remain out of the deck until you issue a 'Majors', 'Minors', " + "'Full', 'Settype', or 'Shuffle' command.\n " + "These are the commands I currently understand:\n\n" + "Majors -- Set deck to deal only from the Major Arcana\n" + "Minors -- Set deck to deal only the pips\n" + "Full -- Set deck to deal both Majors and Minors\n" + "Listtypes -- List the types of decks available for use\n" + "Settype [type] -- Sets to one of the decks listed in Listtypes, eg: /settype " + "jodocamoin Note: This reshuffles the deck\n" + "Draw -- Draw a card\n" + "Help -- This text\n") redis.set(from_id, pickle.dumps(self.deck)) if __name__ == '__main__': token = sys.argv[1] setup_logger('sybil') logging.info('Starting bot with token {}'.format(token)) redis = redis.StrictRedis(host='localhost', port=6379, db=0) sybil = telepot.DelegatorBot( token, [pave_event_space()(per_chat_id(), create_open, Sybil, timeout=600)]) logging.info('Waiting for messages') MessageLoop(sybil).run_as_thread() while 1: time.sleep(1)
msg["location"]["latitude"], msg["location"]["longitude"], 50) if temp == -1: bot.sendMessage( chat_id, phrases["it"]["settings"]["position_error"][0]) else: bot.sendMessage(chat_id, prepare_zone_forecast( temp, source.three_days_forecast( municipalities.getIDr(temp))), reply_markup=make_standard_keyboard( phrases["it"]["main_keyboard"])) database.set_session(chat_id, 0) else: if content_type == "text": bot.sendMessage(chat_id, phrases["it"]["settings"]["first_message"]) bot.sendMessage(chat_id, phrases["it"]["settings"]["first_boot_position"]) database.new_user(chat_id, "null", "null") MessageLoop(bot, {'chat': answer}).run_as_thread() print('Bot attivato') while True: time.sleep(10)
if content_type == 'text': if chat_id not in users: this_user = User(chat_id) users.append(this_user) else: this_user = users[users.index(chat_id)] try: send_message = this_user.say(msg['text'], bot) if send_message: bot.sendMessage( chat_id, msg_state[this_user.state.value], reply_markup=rkb_state[this_user.state.value]) except InputError: bot.sendMessage(chat_id, err_bad_input, reply_markup=rkb_state[this_user.state.value]) except ValueError: bot.sendMessage(chat_id, err_val) bot = telepot.Bot(TOKEN) MessageLoop(bot, handle_chat).run_as_thread() while True: time.sleep(30)
if tag in chats: if chats[tag]['id'] != chat_id: approved.append(chats[tag]['name']) bot.forwardMessage(chats[tag]['id'], chat_id, msg['message_id']) if 'reply_to_message' in msg: bot.forwardMessage( chats[tag]['id'], chat_id, msg['reply_to_message']['message_id']) else: rejected.append(tag) if len(rejected) > 0: bot.sendMessage(chat_id, "Failed to send messages to tags <i>" + ", ".join(rejected) + "</i>", parse_mode="HTML") else: bot.sendMessage( chat_id, "Failed to send a message only with tags which is not a reply to another message" ) bot = telepot.Bot(TOKEN) MessageLoop(bot, handle).run_as_thread() print('Listening ...') # Keep the program running. while 1: time.sleep(10)
reply_markup=listaCall) elif text == "/prossimacall": bot.sendMessage( chat_id, "La prossima call comunitaria sara' quella del " + giornoCall + " " + meseCall + " " + annoCall + ", (il primo venerdi' del mese) alle ore 18:30.\nQuesta e' una stima, potrebbero esserci slittamenti o annullamenti. Per maggiore sicurezza chiedi nel gruppo Home di Mozilla Italia." ) elif text == "/progetti": bot.sendMessage( chat_id, "Questi sono i progetti di mozilla attualmente attivi:", reply_markup=progetti) bot.sendMessage( chat_id, "Questi, invece, sono i progetti della comunità di mozilla italia:", reply_markup=progettimozita) else: bot.sendMessage(chat_id, "Errore: comando non riconosciuto", reply_markup=start) bot = telepot.Bot(TOKEN) MessageLoop(bot, { 'chat': risposte, 'callback_query': risposte }).run_as_thread() while 1: time.sleep(10)
pwm.ChangeDutyCycle(DC) s_mode=0 telegram_bot.sendMessage (chat_id, str("DOOR LOCKED")) elif command == '/photo': telegram_bot.sendDocument(chat_id, document=open('/home/pi/Desktop/image.png')) #choose location of image captured elif command == '/off': telegram_bot.sendMessage (chat_id, str("SYSTEM TURNED OFF")) exit() else: telegram_bot.sendMessage (trail, str("INTRUDER DETECTED")) telegram_bot = telepot.Bot('*******************************') #use your telegram chat_id print (telegram_bot.getMe()) MessageLoop(telegram_bot, action).run_as_thread() print ('Up and Running....') s_mode=0 while(True): keypad() ans=fprint() print("Current stored VALUE ",test) if(password==test or ans): if(s_mode==0): print("Door unlocked ") DC=1./18.*(180)+2 pwm.ChangeDutyCycle(DC) s_mode=1 else: print("Door locked ") DC=1./18.*(50)+2
'Leider ist dein Befehl nicht in der Datenbank verzeichnet.\n Hier nochmal deine Möglichkeiten:\n\n --- Image image_number --- \n Hier erhälst du das Bild mit der Nummer image_number direkt auf dein Handy geschickt.\n Bsp: Image 7\n Um Bildnummer 7 zuerhalten. \n\n --- Stat keyword ---\n Hier erhälst du verschiedene Nutzerstatistiken der Photobox. Als Keyword stehen zur Verfügung:\n name, popular, timebased und taken.\nBsp:\n stat name \n\n --- Help ---\n Hier wird Steven auf seinem Handy benachrichtigt und kommt schnellstmöglichst zu dir. Wenn er nicht kommt solltest du ihn suchen gehen.' ) ### Start Photobox if used as main class if __name__ == '__main__': piBot = tp.Bot(get_ID()) piphotobox = PiPhotobox('admin_id.txt') os.chdir("/media/pi/Marten/photo_folder") try: MessageLoop( piBot, piphotobox.send_image).run_as_thread() # Start the Telegramm chat print('start') while True: time.sleep(1) except KeyboardInterrupt: print('Programm wird beendet') piphotobox.end_connection() ### # Implementierung der User_Stats Database # Einfügen der Funktionen # Einfügen einer KeyboardInterrupt Funtkion # Einfügen der FotoDatabase # mehr try Funktionen