def main(): config = resource_filename(__name__, 'configs.yaml') config = yaml.load(open(config).read()) bot = telepot.DelegatorBot(config['token'], [ (per_inline_from_id(), create_open(NoSpoiler, timeout=30)), (per_chat_id(), create_open(NoSpoiler, timeout=2)), ]) bot.message_loop(run_forever='Running ...')
def __init__(self, token, search, db, server): self.search = search self.db = db self.server = server super(ChatBox, self).__init__(token, [ (per_chat_id(), create_open(T2bot, 90, self.search, self.db, server)), (per_application(), create_open(JobMonitor, self.server, self.db)), ])
def __init__(self, token): self._seen = set() self._store = DBStore() # Imagine a dictionary for storing amounts. super(ChatBox, self).__init__(token, [ # Here is a delegate to specially handle owner commands. (per_chat_id(), create_open(TransferHandler, 60*5, self._store, self._seen)), (per_chat_id(), create_open(OwnerHandler, 60*5, self._store, self._seen)), (per_chat_id(), create_open(FirstTimeHandler, 60*5, self._store, self._seen)) # For senders never seen before, send him a welcome message. # (self._is_newcomer, custom_thread(call(self._send_welcome))), ])
def main(): # Get the dispatcher to register handlers bot = telepot.DelegatorBot(token, [ (per_inline_from_id(), create_open(HowDoIBot, timeout=30)), (per_chat_id(), create_open(HowDoIBot, timeout=10)), ]) logger.info('Starting bot') # bot.message_loop({'inline_query': on_inline_query, # 'chosen_inline_result': on_chosen_inline_result, # 'chat': on_chat_message}, # run_forever='Listening ...') bot.message_loop(run_forever='Listening ...')
def __init__(self, token, owner_id): self._owner_id = owner_id self._seen = set() self._store = UnreadStore() super(ChatBox, self).__init__(token, [ # Here is a delegate to specially handle owner commands. (per_chat_id_in([owner_id]), create_open(OwnerHandler, 20, self._store)), # Seed is always the same, meaning only one MessageSaver is ever spawned for entire application. (lambda msg: 1, create_open(MessageSaver, self._store, exclude=[owner_id])), # For senders never seen before, send him a welcome message. (self._is_newcomer, custom_thread(call(self._send_welcome))), ])
def start(): telepot.DelegatorBot( consts.BOT['TOKEN'], [( per_chat_id(), create_open(Bot, timeout = 10) )] ).message_loop(run_forever = True)
def main(): #orders are managed by user id(chat id), and their specific order #total orders amount is saved into counter. orders = {} order_counter = 0 bot = telepot.DelegatorBot(token, [ (per_chat_id(), create_open(total_execution(orders, order_counter), timeout=10)), ])
def main(): initLogger() logger.info("Application started...") bot = telepot.DelegatorBot( getToken(), [(per_inline_from_id(), create_open(InlineHandler, timeout=None)), ]) logger.info("Bot registered.") bot.notifyOnMessage(run_forever=True) logger.info("Application closing.")
def main(): """Simple main.""" import config bot = telepot.DelegatorBot(config.TG_KEY, [ (per_chat_id(), create_open(WestieBot, timeout=10)), ]) bot.message_loop() while not EXITAPP: time.sleep(1)
def __init__(self, token, owner_id): self._owner_id = owner_id self._seen = set() self._store = UnreadStore() super(ChatBox, self).__init__(token, [ # Here is a delegate to specially handle owner commands. pave_event_space()( per_chat_id_in([owner_id]), create_open, OwnerHandler, self._store, timeout=20), # Only one MessageSaver is ever spawned for entire application. (per_application(), create_open(MessageSaver, self._store, exclude=[owner_id])), # For senders never seen before, send him a welcome message. (self._is_newcomer, custom_thread(call(self._send_welcome))), ])
def __init__(self, token): self._seen = set() self._store = MongoStore() super(ChatBox, self).__init__( token, [ # Here is a delegate to specially handle owner commands. pave_event_space()(per_chat_id_in(self._store.getUsers()), create_open, CommandsBrain, self._store, timeout=100), # Only one MessageSaver is ever spawned for entire application. (per_application(), create_open(MessageSaver, self._store, exclude=[])), # For senders never seen before, send him a welcome message. (self._is_newcomer, print('Welcome mate!')), ])
return False def reply_to_badgay(self, content_type, m): if content_type == 'text' and 'хуй' in m.text: self.sender.sendMessage('НЕ МАТЕРИСЬ, ПИДАРАС!', reply_to_message_id=m.message_id) def on_message(self, msg): content_type, chat_type, chat_id = telepot.glance2(msg) m = telepot.namedtuple(msg, 'Message') if chat_id < 0: # public chat if not self.reply_to_kek(content_type, m): self.reply_to_badgay(content_type, m) else: # private conversation self.reply_to_badgay(content_type, m) """ def on_close(self, exception): if isinstance(exception, telepot.helper.WaitTooLong): bot.notifyOnMessage(run_forever=True) """ TOKEN = '148865285:AAHvwDHJGVrSzEGJ_ToGUxk1RWclvX2L_W4' bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(VeryCruel, timeout=1)), ]) bot.notifyOnMessage(run_forever=True)
import sys import telepot import telepot.helper from telepot.delegate import per_chat_id, create_open class TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(, timeout=10)) ]) bot.message_loop(run_forever=True)
self.sender.sendMessage('Give me a number, please.') return try: guess = int(msg['text']) except ValueError: self.sender.sendMessage('Give me a number, please.') return # check the guess against the answer ... if guess != self._answer: # give a descriptive hint hint = self._hint(self._answer, guess) self.sender.sendMessage(hint) else: self.sender.sendMessage('Correct!') self.close() def on_close(self, exception): if isinstance(exception, telepot.helper.WaitTooLong): self.sender.sendMessage('Game expired. The answer is %d' % self._answer) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Player, timeout=10)), ]) bot.notifyOnMessage(run_forever=True)
if m[0] == u'mojose': r = msg elif user_id == 170378225: ''' if m[1] == u'source': f = open("bot.py", 'r') self.sender.sendDocument(f) elif and m[1] == u'k': process = subprocess.Popen(['/bin/bash'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) process.stdin.write('(sleep 5 && ./bot_killer.sh)&\n') sleep(2) process.kill() #print process.stdout.readline() ''' process = subprocess.Popen(['/bin/bash'], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,bufsize = 1, universal_newlines = True) process.stdin.write(mr+';echo nenio!\n') r = process.stdout.readline() process.kill() if r == "": r = "error!" if len(r) > 4000: r = u'too long!' self.sender.sendMessage(r,parse_mode='HTML') TOKEN = '208704782:AAErS5HiEKZxBuIAwOm4LP3zoZEBqVOSGxQ' bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Babilo, timeout=1)), ]) bot.message_loop(run_forever=True)
def __init__(self, token, cl, srcPath, destPath, baseProb, superUser): super(ChatBot, self).__init__(token, [ (per_application(), create_open(FileClassifier, cl, srcPath, destPath, baseProb, superUser)), ])
import telepot import logging from taxas import Fabrica from telepot.delegate import per_chat_id, create_open SHAZAM_TOKEN = os.environ.get("SHAZAM_TOKEN") logr = logging.getLogger(os.environ.get("LOG-NAME")) class ProcessMessage(telepot.helper.ChatHandler): def __init__(self, seed_tuple, timeout): super(ProcessMessage, self).__init__(seed_tuple, timeout) def on_message(self, msg): try: if msg['text'][0] == "/": taxa = msg['text'][1:].lower() Fabrica.destroy() fabrica = Fabrica(taxa=taxa) self.sender.sendMessage(fabrica.get()) except Exception as e: logr.error(e, exc_info=True) bot = telepot.DelegatorBot(SHAZAM_TOKEN, [ (per_chat_id(), create_open(ProcessMessage, timeout=10)), ]) print('Listening ...') bot.notifyOnMessage(run_forever=True)
class MessageCounter(telepot.helper.ChatHandler): def __init__(self, seed_tuple, timeout): super(MessageCounter, self).__init__(seed_tuple, timeout) self._count = 0 def on_chat_message(self, msg): self._count += 1 self.sender.sendMessage(self._count) TOKEN = sys.argv[1] PORT = int(sys.argv[2]) URL = sys.argv[3] app = Flask(__name__) update_queue = Queue() # channel between `app` and `bot` bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MessageCounter, timeout=10)), ]) bot.message_loop(source=update_queue) # take updates from queue @app.route('/abc', methods=['GET', 'POST']) def pass_update(): update_queue.put(request.data) # pass update to bot return 'OK' if __name__ == '__main__': bot.setWebhook(URL) app.run(port=PORT, debug=True)
# Ignore group messages if not self._suggested_date: return if content_type != 'text': return text = msg['text'] date_string = self._suggested_date.strftime('%A, %Y-%m-%d') if text == 'Decided': THUMB_UP = u'\U0001f44d\U0001f3fb' self._suggestion_editor.editMessageText(date_string + '\n' + THUMB_UP + "Let's meet on this day.") else: CROSS = u'\u274c' self._suggestion_editor.editMessageText(date_string + '\n' + CROSS + "Let me find another day.") # Ignore group messages def on_edited_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg, flavor='edited_chat') print('Edited chat:', content_type, chat_type, chat_id) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_from_id(), create_open(DateCalculator, timeout=20)) ]) bot.message_loop(run_forever='Listening ...')
return self.sender.sendMessage(u'not a command!') cmdline, _, text = msg[u'text'].partition(u'\n') cmd = cmdline.partition(u' ')[0] if cmd not in self.callback: return self.sender.sendMessage(u'unrecognized command!') return self.callback[cmd](msg, text) except Exception, e: logger.error(str(e)) ex_type, ex, tb = sys.exc_info() traceback.print_tb(tb) return self.sender.sendMessage(u'500: server error!') wpbot = telepot.DelegatorBot( config[u'wordpress_com_bot_token'], [(per_chat_id(), create_open(Conversation, timeout=600))]) # flask blueprint app, much like that you get from flask.Flask() wpbotapp = Blueprint(u'wordpress_com_bot', __name__) # keeping a recent_updates heap to ignore same updates from telegram. recent_updates = [] @wpbotapp.route(u'/' + config[u'wordpress_com_bot_token'], methods=[u'POST']) def webhook(): update = request.get_json() if update[u'update_id'] in recent_updates: return u'', 200 heappush(recent_updates, update[u'update_id']) if len(recent_updates) >= 100:
content_type, chat_type, chat_id = telepot.glance(msg) if content_type is 'text': chat_id = msg['chat']['id'] text = msg['text'] if text == "/start": self.sender.sendMessage( "안녕하세요. 주식한당 bot입니다.\n종목코드 및 기업명을 입력하세요.") elif re.match(r'^\d+$', text): stock_price = get_price(text) self.sender.sendMessage(stock_price) # get string not corp code else: corp_codes = get_corp_code(text) if len(corp_codes) >= 1: self.sender.sendMessage("\n".join(corp_codes)) else: self.sender.sendMessage("해당 단어를 포함하는 기업명이 없습니다. 다시 입력하세요.") TOKEN = config.TOKEN bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Telegram, timeout=100)), ]) bot.notifyOnMessage(run_forever=True)
import sys import telepot from telepot.delegate import per_chat_id, create_open from mkr_bot import MkrBot token = sys.argv[1] log_path = sys.argv[2] bot = telepot.DelegatorBot(token, [( per_chat_id(), create_open(MkrBot, timeout=10, log_path=log_path, log_level=10), )]) print(bot.getMe()) bot.notifyOnMessage(run_forever=True)
if content_type != 'text': self.sender.sendMessage('Give me a number, please.') return try: guess = int(msg['text']) except ValueError: self.sender.sendMessage('Give me a number, please.') return # check the guess against the answer ... if guess != self._answer: # give a descriptive hint hint = self._hint(self._answer, guess) self.sender.sendMessage(hint) else: self.sender.sendMessage('Correct!') self.close() def on_close(self, exception): if isinstance(exception, telepot.helper.WaitTooLong): self.sender.sendMessage('Game expired. The answer is %d' % self._answer) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Player, timeout=10)), ]) bot.notifyOnMessage(run_forever=True)
import telepot from telepot.delegate import per_from_id, create_open from enigma import Enigma import resposta teste = Enigma ('teste') teste.setMsg ('Oi, como vai?') class SaBOTagem (telepot.helper.UserHandler): def __init__ (self, *args, **kwargs): """Construtor =P""" super (SaBOTagem, self).__init__ (*args, **kwargs) def on_message (self, msg): """Recebeu msg, testa resposta""" print (msg) def open (self, initMsg, seed): """Hora que abrir canal, Enigma 1""" bot.sendMessage (seed, teste.msg) TOKEN = input () bot = telepot.DelegatorBot (TOKEN, [ (per_from_id (), create_open (SaBOTagem, timeout = 3600)), ]) bot.message_loop (run_forever = True)
import logging import telepot from telepot.delegate import per_from_id, create_open from messageboardbot.app import App from messageboardbot.userhandler import MessageBoardBot logger = logging.getLogger() logger.setLevel(logging.DEBUG) if __name__ == '__main__': configfile = configparser.ConfigParser() configfile.read('config.ini') if not 'bot' in configfile: sys.exit("You need to supply a config file such as in config.sample") config = configfile['bot'] if 'DatabaseURL' in config: app = App(config['DatabaseURL']) elif 'DatabaseFile' in config: app = App(config['DatabaseFile']) else: sys.exit( "You need to add a DatabaseURL or DatabaseFile in the config.") bot = telepot.DelegatorBot(config['TelegramToken'], [ (per_from_id(), create_open(MessageBoardBot, timeout=5 * 60, app=app)), ]) print("Listening...") bot.message_loop(run_forever=True)
""" class InlineHandler(telepot.helper.InlineUserHandler): def __init__(self, seed_tuple, timeout): super(InlineHandler, self).__init__(seed_tuple, timeout) self._answerer = telepot.helper.Answerer(self.bot) def on_inline_query(self, msg): def compute_answer(): query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query') print(self.id, ':', 'Inline Query:', query_id, from_id, query_string) articles = [{'type': 'article', 'id': 'abc', 'title': query_string, 'message_text': query_string}] return articles self._answerer.answer(msg, compute_answer) def on_chosen_inline_result(self, msg): result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(InlineHandler, timeout=10)), ]) bot.message_loop(run_forever=True)
) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print "%s %d: %d: %s: %s" % ( type(self).__name__, self.id, self._count, flavor, telepot.glance2(msg, flavor=flavor), ) def on_close(self, exception): print "%s %d: closed" % (type(self).__name__, self.id) TOKEN = sys.argv[1] bot = telepot.DelegatorBot( TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)), ], ) bot.notifyOnMessage(run_forever=True)
global TOKEN global VALID_USERS TOKEN = config['common']['token'] VALID_USERS = config['common']['valid_users'] config = parseConfig(CONFIG_FILE) if not bool(config): print ("Err: Setting file is not found") exit() getConfig(config) #TOKEN = '199048259:AAGtyE1_vvXFMEPQ24a3-qf8s4ifqPpP85U' bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ClienHelper, timeout=120)), ]) print(bot) bot.notifyOnMessage(run_forever=True) #curl "https://api.telegram.org/bot199048259:AAGtyE1_vvXFMEPQ24a3-qf8s4ifqPpP85U/sendMessage?chat_id=62233150&text=$startMsg" #bot.sendMessage(my_chat_id, startMsg) #show_keyboard = {'keyboard': [['Yes','No'], ['Maybe','Maybe not']]}
self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % self._votes[from_id]) else: self.bot.answerCallbackQuery(query_id, text='Ok') self._votes[from_id] = query_data if len(self._votes) >= self._members_count: self._editor.editMessageReplyMarkup(reply_markup=None) self.sender.sendMessage('Everyone has voted. Thank you.') self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes()) def on_timeout(self, exception): self._editor.editMessageReplyMarkup(reply_markup=None) self.sender.sendMessage('Time is up.') self.sender.sendMessage('Yes: %d\nNo: %d\nSilent: %d' % self._count_votes()) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(types=['group']), create_open(VoteCounter, timeout=20)), ]) bot.message_loop() print('Listening ...') while 1: time.sleep(10)
all_games[game_id].player_list.append(Player(msg['from']['id'], msg['from']['first_name'])) start_url = telegram_base_url + bot_name + '?start=' + game_id.__str__() self.sender.sendMessage(text=bot_invite_player % (chkNConv(msg['from']['first_name']), chkNConv(bot_name), chkNConv(start_url))) def on_message(self, msg): print(u'on_message() is being called') flavor = telepot.flavor(msg) # normal message if chkNConv(flavor) == u'normal': content_type, chat_type, _chat_id = telepot.glance2(msg) print('Normal Message:', content_type, chat_type, _chat_id, '; message content: ', msg) if content_type == 'text': if self._convert_type == ConverType.nothing: if chkNConv(msg['text']) == u'/start': self.sender.sendMessage(text=bot_starting_script) elif chkNConv(msg['text']) == u'/newgame' or chkNConv(msg['text']) == u'/newgame@' + chkNConv(bot_name): self.create_game(msg=msg) else: raise telepot.BadFlavor(msg) TOKEN = sys.argv[1] # get token from command-line bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(LiarsDiceBot, timeout=120)),]) print('Listening ...') bot.notifyOnMessage(run_forever=True)
query_string) self._count += 1 text = '%d. %s' % (self._count, query_string) articles = [ InlineQueryResultArticle( id='abc', title=text, input_message_content=InputTextMessageContent( message_text=text)) ] return articles self.answerer.answer(msg, compute) def on_chosen_inline_result(self, msg): result_id, from_id, query_string = telepot.glance( msg, flavor='chosen_inline_result') print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] # get token from command-line bot = telepot.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(QueryCounter, timeout=10)), ]) bot.message_loop(run_forever='Listening ...')
import sys import telepot from telepot.delegate import per_chat_id, create_open from mkr_bot import MkrBot token = sys.argv[1] log_path = sys.argv[2] bot = telepot.DelegatorBot(token, [(per_chat_id(), create_open(MkrBot, timeout=10, log_path=log_path, log_level=10))]) print(bot.getMe()) bot.notifyOnMessage(run_forever=True)
if r == '': raise except Exception as e: if re.search(u'(نظرت|نظر تو) (در مورد|درباره|دربارهٔ|درباره ی|دربارهی|راجع به|راجب) .* (چیست|چیه)', mr): r = choice([u'در مورد همه چی باید نظر بدم؟!', u'نظر خاصی ندارم.', u'در این زمینه صاحب نظر نیستم.']) elif re.search(u'؟$', mr): r = choice([u'چرا میپرسی؟', u'نپرس!', u'نمیدونم.']) elif re.search(u'!$', mr): r = choice([u'عجب!', u'چه جالب!']) elif re.search(u'\.$', mr): r = choice([u'این که پایان جملهت نقطه گذاشتی خیلی عالیه! ولی معنی جملهت رو نمیفهمم. یادم بده.']) else: r = u'نمیفهمم چی میگی. بیا خصوصی یادم بده!' #print 'erorr:', e #r = e if len(r) > 0: self.sender.sendMessage(r,parse_mode='HTML') if __name__ == "__main__": if len(sys.argv) == 2: if sys.argv[1] == 'd': TOKEN = '185401678:AAF_7PbchYOIDAKpy6lJqX7z01IsFgDTksA' else: o = open(os.path.join(os.environ['OPENSHIFT_DATA_DIR'], 'token')) t = o.read() TOKEN = t[:-1] o.close() bot = telepot.DelegatorBot(TOKEN, [(per_chat_id(), create_open(Babilo, timeout=1)),]) bot.message_loop(run_forever=True)
options, args = parser.parse_args() try: loglevel = getattr(logging, options.debug) except AttributeError: loglevel = { 3: logging.CRITICAL, 2: logging.ERROR, 1: logging.WARNING, 0: logging.INFO, -1: logging.DEBUG, }[int(options.debug)] setup_logging(loglevel, options.printtostdout) logger.info('Starting up...') config_json = parse_config(CONFIG_FILE) if not bool(config_json): logger.error("Err: Setting file is not found") exit() setup(config_json) bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Torrenter, timeout=120)), ]) logger.info('Ready to ROCK!') bot.notifyOnMessage(run_forever=True)
def on_callback_query(self, msg): query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query') if query_data == 'yes': # hide inline keyboard self._editor.editMessageReplyMarkup(reply_markup=None) self.sender.sendMessage('Thank you!') self.close() else: self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.') # hide inline keyboard self._editor.editMessageReplyMarkup(reply_markup=None) self._count += 1 sent = self.sender.sendMessage('%d. Would you marry me?' % self._count, reply_markup=self._keyboard) self._editor = telepot.helper.Editor(self.bot, sent) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(types=['private']), create_open(Lover, timeout=10)), ]) bot.message_loop() print('Listening ...') while 1: time.sleep(10)
js = json.loads(f.read()) f.close() return js def getConfig(config): global TOKEN global VALID_USERS TOKEN = config['common']['token'] VALID_USERS = config['common']['valid_users'] config = parseConfig(CONFIG_FILE) if not bool(config): print ("Err: Setting file is not found") exit() getConfig(config) bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MyHomeHelper, timeout=120)), ]) bot.notifyOnMessage(run_forever=True)
Command.process_commands(self, bot, msg) ''' # Callback_query will be answered by CallbackBot. MainBot ignores such queries. def on_callback_query(self, msg): return ''' def on_callback_query(self, msg): query_id, from_id, data = telepot.glance(msg, flavor='callback_query') print "---- CALLBACK QUERY ----" CallbackQueries.on_answer(self, bot, data, query_id, msg['message']['message_id']) def on_close(self, exception): if isinstance(exception, telepot.exception.WaitTooLong): print "---- SESSION EXPIRED ----" self.sender.sendMessage('Session expired') bot = telepot.DelegatorBot(TOKEN, [ # # IMPORTANT: CallbackBot will NOT WORK if the program has been closed. You need one message to init it. # Assumption that timeout=None means the Bot will run forever # Note also: the message will run through CallbackBot first and then to MyBot # # (per_application(), create_open(CallbackBot, timeout=None)), (per_chat_id(), create_open(MainBot, timeout=None)), ]) # CANNOT put bot.message_loop() here or there will be a bug
super(MessageCounter, self).__init__(seed_tuple, timeout) self._count = 0 def on_chat_message(self, msg): self._count += 1 self.sender.sendMessage(self._count) TOKEN = sys.argv[1] PORT = int(sys.argv[2]) URL = sys.argv[3] app = Flask(__name__) update_queue = Queue() # channel between `app` and `bot` bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MessageCounter, timeout=10)), ]) bot.message_loop(source=update_queue) # take updates from queue @app.route('/abc', methods=['GET', 'POST']) def pass_update(): update_queue.put(request.data) # pass update to bot return 'OK' if __name__ == '__main__': bot.setWebhook(URL) app.run(port=PORT, debug=True)
self.id, ':', flavor, '+1', ':', ', '.join([ str(self._counts[f]) for f in ['chat', 'inline_query', 'chosen_inline_result'] ])) # Have to answer inline query to receive chosen result if flavor == 'inline_query': def compute_answer(): query_id, from_id, query_string = telepot.glance(msg, flavor=flavor) articles = [{ 'type': 'article', 'id': 'abc', 'title': query_string, 'message_text': query_string }] return articles self._answerer.answer(msg, compute_answer) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_from_id(), create_open(UserTracker, timeout=20)), ]) bot.message_loop(run_forever=True)
if content_type != 'text': return text = msg['text'] date_string = self._suggested_date.strftime('%A, %Y-%m-%d') if text == 'Decided': THUMB_UP = u'\U0001f44d\U0001f3fb' self._suggestion_editor.editMessageText(date_string + '\n' + THUMB_UP + "Let's meet on this day.") else: CROSS = u'\u274c' self._suggestion_editor.editMessageText(date_string + '\n' + CROSS + "Let me find another day.") # Ignore group messages def on_edited_chat_message(self, msg): content_type, chat_type, chat_id = telepot.glance(msg, flavor='edited_chat') print('Edited chat:', content_type, chat_type, chat_id) TOKEN = sys.argv[1] bot = telepot.DelegatorBot( TOKEN, [(per_from_id(), create_open(DateCalculator, timeout=20))]) bot.message_loop(run_forever='Listening ...')
'_': lambda msg: True }]) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print '%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance(msg, flavor=flavor)) # Do some simple stuff for every message, to be paired with per_message() def simple_function(seed_tuple): bot, msg, id = seed_tuple print 'Simply print:', msg TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)), (per_application(), create_open(OnlyOneInstance)), (per_message(), call(simple_function)), ]) bot.message_loop(run_forever=True)
def get_link(nth): item = soup.findAll('item')[nth] link = re.search(r'http://www.farsnews.com/(\d+)', unicode(item)).group(0) return link r = unicode(all_title[2]).replace('<title>', '<a href="%s">'%get_link(0), 2).replace('</title>', '</a>') + '\n\n' + \ unicode(all_title[3]).replace('<title', '<a href="%s"'%get_link(1), 2).replace('</title>', '</a>') + '\n\n' + \ unicode(all_title[4]).replace('<title', '<a href="%s"'%get_link(2), 2).replace('</title>', '</a>') if r == '': try: hoy_output = (Hoy.select().join(Chat).join(User).where( User.user == mr[4:]))[0].hoy r = choice(ast.literal_eval(hoy_output)) except: r = u'نمیفهمم چی میگی.' self.sender.sendMessage(r, parse_mode='HTML') #TOKEN = sys.argv[1] # get token from command-line TOKEN = '238806755:AAH1vINCnTj8Dfka8hl3Qza6ih28xze9PgM' bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Babilo, timeout=1)), ]) #bot = telepot.async.Bot(TOKEN, ) #bot.setWebhook('https://bot-ajor.rhcloud.com') #bot.notifyOnMessage(run_forever=True) bot.message_loop(run_forever=True)
if 'from' in msg.keys(): if 'username' in msg['from'].keys(): info['username'] = msg['from']['username'].encode('utf-8') if 'first_name' in msg['from'].keys(): info['first_name'] = msg['from']['first_name'].encode('utf-8') if 'last_name' in msg['from'].keys(): info['last_name'] = msg['from']['last_name'].encode('utf-8') total = db_ops.add_user(self.user_id) info['Total_Users'] = total self.new_user = False output = "\n".join(["{k}: {v}".format(k=key, v=info[key]) for key in info.iterkeys()]) bot.sendMessage(users_info_group_id, _now + output) # json.dumps(info, indent=2, separators=(',', ': '), encoding='utf-8')) # .encode('utf-8')) if __name__ == "__main__": TOKEN = '228572738:AAFAZf9U3i1yt1si2ft4Cz-94cLEYmTiRx4' # RavanYaarDevBot # TOKEN = '232659175:AAHpIcg5Dax6r_15ZlOwTwSkuUEeE1wVWME' # RavanYaarBot # bot = telepot.Bot(TOKEN) users_info_group_id = -116540547 debugging_group_id = -165690520 bot = telepot.DelegatorBot(TOKEN, [ (per_from_id(flavors='all'), create_open(UserHandlerSubclass, timeout=20)), # (per_application(), create_open(OneInstanceOnly)), # (per_message(), call(simple_function)), ]) print "Listening..." bot.message_loop(run_forever=True) message_with_inline_keyboard = None
def parseConfig(filename): f = open(filename, 'r') js = json.loads(f.read()) f.close() return js def getConfig(config): global TOKEN global AGENT_TYPE global VALID_USERS TOKEN = config['common']['token'] AGENT_TYPE = config['common']['agent_type'] VALID_USERS = config['common']['valid_users'] if AGENT_TYPE == 'transmission': global transmission_user global transmission_password global transmission_port TRANSMISSION_USER = config['for_transmission']['transmission_user'] TRANSMISSION_PASSWORD = config['for_transmission']['transmission_password'] TRANSMISSION_PORT = config['for_transmission']['transmission_port'] config = parseConfig(CONFIG_FILE) if not bool(config): print ("Err: Setting file is not found") exit() getConfig(config) bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(Torrenter, timeout=120)), ]) bot.notifyOnMessage(run_forever=True)
class MessageProcessor(telepot.helper.ChatHandler): '''Initiate chat socket for a client and respond to the input query''' def __init__(self, seed_tuple, timeout): super(MessageProcessor, self).__init__(seed_tuple, timeout) def on_chat_message(self, msg): '''process and response message''' ntuple = Message(**msg) if telepot.glance(msg)[0] == 'text': if any(q in ntuple.text for q in ACTION_DICT.keys()): response = perform_action(ntuple.text, ntuple.from_.id) else: response = KERNEL.respond(ntuple.text) #if not response: #response = self.sender.sendMessage( # chat_id, 'I do not understand your last message.', reply_to_message_id=msg_id) self.sender.sendMessage(response) BOT = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MessageProcessor, timeout=10)), ]) BOT.message_loop(run_forever=True)
def on_close(self, exception): print '%s %d: closed' % (type(self).__name__, self.id) # Captures inline-related messages from a user, to be paired with per_inline_from_id() class UserHandlerSubclassInlineOnly(telepot.helper.UserHandler): def __init__(self, seed_tuple, timeout): super(UserHandlerSubclassInlineOnly, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result']) self._count = 0 def on_message(self, msg): self._count += 1 flavor = telepot.flavor(msg) print '%s %d: %d: %s: %s' % (type(self).__name__, self.id, self._count, flavor, telepot.glance(msg, flavor=flavor)) def on_close(self, exception): print '%s %d: closed' % (type(self).__name__, self.id) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(ChatHandlerSubclass, timeout=10)), (per_from_id(), create_open(UserHandlerSubclass, timeout=20)), (per_inline_from_id(), create_open(UserHandlerSubclassInlineOnly, timeout=10)), ]) bot.notifyOnMessage(run_forever=True)
""" class InlineHandler(telepot.helper.UserHandler): def __init__(self, seed_tuple, timeout): super(InlineHandler, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result']) def on_message(self, msg): flavor = telepot.flavor(msg) if flavor == 'inline_query': query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor) print(self.id, ':', 'Inline Query:', query_id, from_id, query_string) articles = [{'type': 'article', 'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}] self.bot.answerInlineQuery(query_id, articles) print(self.id, ':', 'Answers sent.') elif flavor == 'chosen_inline_result': result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor) print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_inline_from_id(), create_open(InlineHandler, timeout=10)), ]) bot.notifyOnMessage(run_forever=True)
def on_callback_query(self, msg): print "I shall do nothing from now on. Let CallbackBot handle the job" def callback_function(msg): flavor = telepot.flavor(msg) if flavor == 'callback_query': print "callback!!" elif flavor == 'chat': print "normal message" return def hello_world(self): print "hello" print self mycallback = {'chat': hello_world, 'callback_function': callback_function} # callback_bot = telepot.Bot(TOKEN) bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(MyBot, timeout=15)), ]) bot.message_loop(mycallback, run_forever=True) ''' bot = CallbackBot(TOKEN) bot.message_loop(callback_function, run_forever=True) '''
# keep track of how many messages of each flavor self._counts = {'normal': 0, 'inline_query': 0, 'chosen_inline_result': 0} def on_message(self, msg): flavor = telepot.flavor(msg) self._counts[flavor] += 1 # Display message counts separated by flavors print(self.id, ':', flavor, '+1', ':', ', '.join([str(self._counts[f]) for f in ['normal', 'inline_query', 'chosen_inline_result']])) # Have to answer inline query to receive chosen result if flavor == 'inline_query': query_id, from_id, query_string = telepot.glance(msg, flavor=flavor) articles = [{'type': 'article', 'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}] self.bot.answerInlineQuery(query_id, articles) TOKEN = sys.argv[1] bot = telepot.DelegatorBot(TOKEN, [ (per_from_id(), create_open(UserTracker, timeout=20)), ]) bot.notifyOnMessage(run_forever=True)
# Simple Hangman Bot made for the 11th March CoderDojo Master # Author: Giovanni Riva && Giovanni De Toni # Mail: giovannimaria.riva at studenti.unitn.it # giovanni.detoni at studenti.unitn.it import sys, time, telepot from telepot.delegate import per_chat_id, create_open from CoderDojoBot import CoderDojoBot # Initialize the bot and start the loop TOKEN = '187053440:AAEya33XgwHP8zcLXo1Ny5yOpJ2XvkwVRBU' bot = telepot.DelegatorBot(TOKEN, [ (per_chat_id(), create_open(CoderDojoBot, timeout=60)), ]) bot.notifyOnMessage(run_forever=True)