Example #1
0
def webhook (request, bot_token):
    
    #verifico la validità del token
    bot = DjangoTelegramBot.getBot(bot_token, safe=False)
    if bot is None:
        logger.warn('Request for not found token : {}'.format(bot_token))
        return JsonResponse({})
    
    try:
        data = json.loads(request.body.decode("utf-8"))

    except:
        logger.warn('Telegram bot <{}> receive invalid request : {}'.format(bot.username, repr(request)))
        return JsonResponse({})

    dispatcher = DjangoTelegramBot.getDispatcher(bot_token, safe=False)
    if dispatcher is None:
        logger.error('Dispatcher for bot <{}> not found : {}'.format(bot.username, bot_token))
        return JsonResponse({})
        
    try:
        update = telegram.Update.de_json(data)
        dispatcher.process_update(update)
        logger.debug('Bot <{}> : Processed update {}'.format(bot.username, update))
    # Dispatch any errors
    except TelegramError as te:
        logger.warn("Bot <{}> : Error was raised while processing Update.".format(bot.username))
        dispatcher.dispatchError(update, te)

    # All other errors should not stop the thread, just print them
    except:
        logger.error("Bot <{}> : An uncaught error was raised while processing an update\n{}".format(bot.username, sys.exc_info()[0]))
    
    finally:
        return JsonResponse({})
Example #2
0
 def get_updater(self, username=None, token=None):
     updater = None
     if username is not None:
         updater = DjangoTelegramBot.get_updater(bot_id=username)
         if not updater:
             self.stderr.write("Cannot find default bot with username {}".format(username))
     elif token:
         updater = DjangoTelegramBot.get_updater(bot_id=token)
         if not updater:
             self.stderr.write("Cannot find bot with token {}".format(token))
     return updater
Example #3
0
def index(request):
    bot = DjangoTelegramBot.getBot(bot_id=bot_token, safe=False)
    try:
        data = json.loads(request.body.decode("utf-8"))
    except:
        return JsonResponse({})

    dispatcher = DjangoTelegramBot.getDispatcher(bot_token, safe=False)

    try:
        update = telegram.Update.de_json(data, bot)
        dispatcher.process_update(update)
    except TelegramError as te:
        dispatcher.dispatchError(update, te)

    return JsonResponse({})
Example #4
0
    def handle(self, *args, **options):
        tournament = Tournament.objects.get(pk=options['tournament_id'])
        bot_name = DjangoTelegramBot.getBot().username

        for team in tournament.get_teams():
            for speaker in team.team.get_speakers():

                if speaker.telegram_id:
                    continue

                html_content = render_to_string(
                    'tournament/start_tournament_email.html', {
                        'tournament': tournament,
                        'bot_name': bot_name,
                        'token': TelegramToken.generate(speaker).value,
                    })

                text_content = strip_tags(html_content)
                logging.info(html_content)
                logging.info(text_content)
                msg = EmailMultiAlternatives(tournament.name, text_content,
                                             settings.EMAIL_HOST_USER,
                                             [speaker.email])
                msg.attach_alternative(html_content, 'text/html')
                msg.send()
Example #5
0
def set_thread_locals(base: Dispatcher or Bot or Update, update=None):
    """Set necessary thread locals for this thread

    This will set at least the dispatcher and if update is given also the update
    """
    from bot import telegrambot as tb

    if isinstance(base, Dispatcher):
        dispatcher = base
    elif isinstance(base, Bot):
        dispatcher = DjangoTelegramBot.get_dispatcher(base.token)
    elif isinstance(base, Update) and base.effective_chat:
        dispatcher = DjangoTelegramBot.get_dispatcher(
            base.effective_chat.bot.token)

    tb.my_bot.threadlocal.dispatcher = dispatcher
    tb.my_bot.threadlocal.update = update
Example #6
0
def webhook(request, bot_token):
    bot = DjangoTelegramBot.getBot(bot_id=bot_token, safe=False)
    if bot is None:
        logger.warn("Request for not found token : {}".format(bot_token))
        return JsonResponse({})

    try:
        data = json.loads(request.body.decode("utf-8"))

    except:
        logger.warn(
            "Telegram bot <{}> receive invalid request : {}".format(
                bot.username, repr(request)
            )
        )
        return JsonResponse({})

    dispatcher = DjangoTelegramBot.getDispatcher(bot_token, safe=False)
    if dispatcher is None:
        logger.error(
            "Dispatcher for bot <{}> not found : {}".format(bot.username, bot_token)
        )
        return JsonResponse({})

    try:
        update = telegram.Update.de_json(data, bot)
        dispatcher.process_update(update)
        logger.debug("Bot <{}> : Processed update {}".format(bot.username, update))
    # Dispatch any errors
    except TelegramError as te:
        logger.warn(
            "Bot <{}> : Error was raised while processing Update.".format(bot.username)
        )
        dispatcher.dispatchError(update, te)

    # All other errors should not stop the thread, just print them
    except:
        logger.error(
            "Bot <{}> : An uncaught error was raised while processing an update\n{}".format(
                bot.username, sys.exc_info()[0]
            )
        )

    finally:
        return JsonResponse({})
Example #7
0
def main():
    logger.info("Loading handlers for bilanzen")
    dp = DjangoTelegramBot.getDispatcher(botname)
    commands = [start, stop, help]
    for cmd in commands:
        pass_args = cmd.pass_args if hasattr(cmd, 'pass_args') else False
        name = cmd.command if hasattr(cmd, 'command') else cmd.__name__
        dp.add_handler(CommandHandler(name, cmd, pass_args=pass_args))
    dp.add_error_handler(error)
Example #8
0
def main():
    print('starting')
    logger.info("Loading handlers for emorun")
    dp = DjangoTelegramBot.getDispatcher('emorunbot')
    for cmd in cmds:
        name = cmd.command if hasattr(cmd, 'command') else cmd.__name__
        dp.add_handler(CommandHandler(name, cmd))
        print('added: '+name)
    # dp.add_error_handler(error)
    dp.add_handler(CallbackQueryHandler(cb))
Example #9
0
def main():
    logger.debug("Loading handlers for kuhsagbot")
    dp = DjangoTelegramBot.getDispatcher('kuhsagbot')
    # dp = DjangoTelegramBot.getDispatcher('telebotterbot')
    for cmd in commands:
        pass_args = cmd.pass_args if hasattr(cmd, 'pass_args') else False
        name = cmd.command if hasattr(cmd, 'command') else cmd.__name__
        dp.add_handler(CommandHandler(name, cmd, pass_args=pass_args))
    #dp.add_handler(InlineQueryHandler(inlinequery))
    #dp.add_handler(CallbackQueryHandler(callback))
    #dp.add_error_handler(error)
    dp.add_handler(InlineQueryHandler(inlinequery))
    dp.add_error_handler(error)
Example #10
0
def main():
    logger.info("Loading handlers for radtourbot")
    dp = DjangoTelegramBot.getDispatcher('radtourbot')
    dp.add_error_handler(error)
    # on different commands - answer in Telegram
    for cmd in commands:
        pass_args = cmd.pass_args if hasattr(cmd, 'pass_args') else False
        name = cmd.command if hasattr(cmd, 'command') else cmd.__name__
        dp.add_handler(CommandHandler(name, cmd))
    #dp.add_handler(CommandHandler('start', start))
    #dp.add_handler(CommandHandler('help', help))
    logging.info('trying to add csv')
    dp.add_handler(MessageHandler(Filters.document, file))
    dp.add_handler(CallbackQueryHandler(callback))
def main():
    logger.info("Loading handlers for telegram bot")

    # Default dispatcher (this is related to the first bot in settings.DJANGO_TELEGRAMBOT['BOTS'])
    #dp = DjangoTelegramBot.dispatcher
    # To get Dispatcher related to a specific bot
    dp = DjangoTelegramBot.getDispatcher(
        'Enter Your Bot Token Here')  #get by bot token
    # dp = DjangoTelegramBot.getDispatcher('BOT_n_username')  #get by bot username

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("contactus", contact))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler([Filters.text], echo))

    # log all errors
    dp.add_error_handler(error)
Example #12
0
def main():
    log.warning("......Loading handlers for telegram bot")

    # Default dispatcher (this is related to the first bot in settings.DJANGO_TELEGRAMBOT['BOTS'])
    # dp = DjangoTelegramBot.dispatcher
    # To get Dispatcher related to a specific bot
    # dp = DjangoTelegramBot.getDispatcher('BOT_n_token')     #get by bot token
    dp = DjangoTelegramBot.getDispatcher(
        'NewPublisherBot')  #get by bot username

    # on different commands - answer in Telegram
    # dp.add_handler(CommandHandler("wallet", wallet, pass_args=True))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("status", status))
    dp.add_handler(CommandHandler("subscribe", subscription))
    dp.add_handler(CommandHandler("unsubscribe", subscription))
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(button_handler)

    dp.add_handler(CallbackQueryHandler(button))

    # From libs
    # dp.add_handler(CommandHandler(GROUP[1:], group, pass_args=True))

    # dp.add_handler(CommandHandler(RESTRICT[1:], restrictUser, pass_args=True))
    # dp.add_handler(CommandHandler(BAN[1:], banUser, pass_args=True))
    # dp.add_handler(CommandHandler(UNBAN[1:], unbanUser, pass_args=True))

    # dp.add_handler(CommandHandler(TEST_COMMAND[1:], test_command, pass_args=True))

    # ConversationHandler()
    # on noncommand i.e message - echo the message on Telegram
    # dp.add_handler(MessageHandler([Filters.text], echo))
    # dp.add_handler(MessageHandler([], in_out))

    # Filters.successful_payment
    # dp.add_handler(MessageHandler([], create_member))
    # dp.add_handler(MessageHandler([], test_msg))

    # log all errors
    dp.add_error_handler(error)
Example #13
0
 def setUp(self):
     self.app = DjangoTelegramBot.create('django_telegrambot')