def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', default=join('config', 'prod.yml')) args = parser.parse_args() with open(args.config) as config_file: config = yaml.load(config_file.read()) # Is it main app or test app is_main = config['pockebot_is_main'] # Got Telegram bot access token # config_manager = db.PockebotDBSlave(config) # token = config_manager.get_bot_token() token = config['telegram_token'] bot = telepot.aio.DelegatorBot(token, [ (per_from_id(), create_open(PocketBot, timeout=60, is_main=is_main, config=config)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.message_loop()) print('Listening ...') loop.run_forever()
# 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)
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 __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.glance2(msg, flavor=flavor))) def on_close(self, exception): print('%s %d: closed' % (type(self).__name__, self.id)) TOKEN = sys.argv[1] bot = telepot.async.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)), ]) loop = asyncio.get_event_loop() loop.create_task(bot.messageLoop()) print('Listening ...') loop.run_forever()
## Journal. try: print("\033[33m>>>\033[0m %s\n\033[33mBot\033[0m: Closed an delegator with @\033[34m%s\033[0m by calling on_close()."%(self._now, self._username)) except: print("\033[33m>>>\033[0m %s\n\033[33mBot\033[0m: Closed an delegator by calling on_close()."%(self._now)) print("--------------------------------------------") ### Now it starts run. print("Getting bot information...") ### Generate a bot object. bot = telepot.DelegatorBot( TOKEN, [ pave_event_space()( per_from_id(), create_open, TeleBot, timeout=30 ) ] ) ### Now it prints your bot information. try: info = bot.getMe() except KeyboardInterrupt: exit() except: conf_rewrite = False print("\033[46m\033[31mERROR\033[0m: Your token is invaild.") print("Please check what your config file \"%s\" contains."%(config_file))
'_': 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)
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)
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)
# 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 ...')
) def on_close(self, exception): print "%s %d: closed" % (type(self).__name__, self.id) class InlineOnlyHandler(telepot.helper.UserHandler): def __init__(self, seed_tuple, timeout): super(InlineOnlyHandler, self).__init__(seed_tuple, timeout, flavors=["inline_query"]) self._count = 0 def on_message(self, msg): self._count += 1 print "%s %d: %d: %s" % (type(self).__name__, self.id, self._count, telepot.glance2(msg, flavor="inline_query")) 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(MessageOnlyHandler, timeout=10)), (per_from_id(), create_open(MessageAndInlineHandler, timeout=20)), (per_inline_from_id(), create_open(InlineOnlyHandler, 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)
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 ...')
import cmath import time import telepot from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove from telepot.delegate import per_from_id, per_chat_id, create_open, pave_event_space, include_callback_query_chat_id class solo(telepot.helper.UserHandler): def __init__(self, *args, **kwargs): super(solo, self).__init__(*args, **kwargs) def on_caht_messgae(self, msg): self.sender.sendMessage(msg) class tester(telepot.helper.ChatHandler): def __init__(self, *args, **kwargs): super(tester, self).__init__(*args, **kwargs) def on_chat_message(self, msg): self.sender.sendMessage("say whut") solo.sender.sendMessage("I hate you") TOKEN = "347707642:AAGeEmnFe6q-FkkV_D9V78RCk389E7Rm81Q" # NIppleskittles bot = telepot.DelegatorBot(TOKEN, [ pave_event_space()(per_chat_id(), create_open, tester, timeout=10), pave_event_space()(per_from_id(), create_open, solo, timeout=12), ])