Forums

Problem while using telepot to create a DelegatorBot

I tried to create DelegatorBot using telepot. But for some reason it doesn't work. The "outer" is printed but not the "inner". Any help?

from flask import Flask, request
import telepot
import urllib3
from telepot.loop import OrderedWebhook
from telepot.delegate import per_chat_id, create_open, pave_event_space

class MessageCounter(telepot.helper.ChatHandler):
    def __init__(self, *args, **kwargs):
        super(MessageCounter, self).__init__(*args, **kwargs)
        self._count = 0

    def on_chat_message(self, msg):
        print("inner")
        self._count += 1
        self.sender.sendMessage(self._count)

proxy_url = "http://proxy.server:3128"
telepot.api._pools = {
'default': urllib3.ProxyManager(proxy_url=proxy_url, num_pools=3, maxsize=10, retries=False, timeout=30),
}
telepot.api._onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=proxy_url, num_pools=1, maxsize=1, retries=False, timeout=30))

TOKEN = "MY_TOKEN"
secret = "MY_SECRET"

app = Flask(__name__)

bot = telepot.DelegatorBot(TOKEN, [
    pave_event_space()(
        per_chat_id(), create_open, MessageCounter, timeout=10),
])

webhook = OrderedWebhook(bot)

@app.route('/{}'.format(secret), methods=['GET', 'POST'])
def pass_update():
    webhook.feed(request.data)
    print("outer")
    return 'OK'

try:
    bot.setWebhook('MY_URL/{}'.format(secret))
# Sometimes it would raise this error, but webhook still set successfully.
except telepot.exception.TooManyRequestsError:
    pass

webhook.run_as_thread()

The "outer" working suggests that you're running this in a web app. I don't see any route that would lead to the "inner" being called. You can't mix webhook and message loop-handling in a web app - only the webhook part will work. See http://blog.pythonanywhere.com/148/ for details about the differences.

I need to combine webhook with bot for each per_chat_id(). How to do so?

I would assume that chat Id is in the webhook message, so use it directly in your webhook view or something like that.

This is example from telepot's github: DelegatorBot - Webhook

You can see there they used webhook and DelegatorBot together. But this example doesn't work on pythonanywhere.

deleted

Ah, I think I see. The OrderedWebhook class is a server they've written to implement a webhook receiver, and I don't think it's WSGI-based -- instead, it's meant to run in its own event loop. That means it's not compatible with the PythonAnywhere web hosting system.