如何将Flask应用程序与BaleBot一起使用以向用户发送消息

时间:2018-06-24 04:25:57

标签: python bale-messenger balebot

我想使用Flask应用程序来获取发送消息给Bale用户的请求。

此代码有效! BaleBot响应用户消息和Flask应用程序响应请求。但bot.send_message中的def send_to_user无法正常工作!

例如,如果我用Bale向我的机器人发送了一条消息(任何东西),他的响应。 并且如果我向Flask发送这样的请求,例如curl -X POST 127.0.0.1:5000/send/user -d 'bale_id=1533910422&access_hash=6644828719985087310&message=text',则Flask做出了回应。

import os

import asyncio
from flask import Flask
from flask import request
from balebot.handlers import *
from balebot.filters import *
from balebot.models.base_models import Peer
from balebot.models.messages import *
from balebot.updater import Updater
from balebot.config import Config
from threading import Thread

import zbxbale_settings

Config.log_level = zbxbale_settings.LOG_LEVEL

updater = Updater(token=zbxbale_settings.bale_key, loop=asyncio.get_event_loop())
# updater = Updater(token=zbxbale_settings.bale_key)
dispatcher = updater.dispatcher
bale_bot = updater.bot


def success(result, err):
    print("success : ", result)
    print("success : ", err)


def failure(result, err):
    print("failure : ", result)


@dispatcher.command_handler("/start")
def start_command(bot, update):
    message = update.get_effective_message()
    bot.respond(update, message, success_callback=success, failure_callback=failure)


@dispatcher.default_handler()
def default_handler(bot, update):
    message = update.get_effective_message()
    message.text += " not recognized"
    bot.respond(update, message, success_callback=success, failure_callback=failure)


app = Flask(__name__)


@app.route("/")
def hello():
    return "Hello"


@app.route("/send/user", methods=['POST'])
def send_to_user():
    bale_id = request.form['bale_id']
    access_hash = request.form['access_hash']
    message = request.form['message']
    p = Peer('User', bale_id, access_hash)
    m = TextMessage(message)
    bale_bot.send_message(m, p, success_callback=success, failure_callback=failure)
    return "Hello World!"


@app.route("/send/group", methods=['POST'])
def send_to_group():
    bale_id = request.form['bale_id']
    access_hash = request.form['access_hash']
    return "Hello World!"


from multiprocessing import Process


p = Process(target=app.run, args=())
q = Process(target=updater.run, args=())

q.start()
p.start()
# q.join()
# p.join()
# app.run()
# updater.run()

p = Peer('User', "1533910422", "6644828719985087310")
m = TextMessage("salam")
updater.bot.send_message(m, p, success_callback=success, failure_callback=failure)

2 个答案:

答案 0 :(得分:4)

@ehsan-barkhordar的帮助下,此代码已编写且正确:

import pykka

import asyncio
from flask import Flask
from flask import request
from balebot.handlers import *
from balebot.filters import *
from balebot.models.base_models import Peer
from balebot.models.messages import *
from balebot.updater import Updater

updater = Updater(token="token", loop=asyncio.get_event_loop())
dispatcher = updater.dispatcher
bale_bot = updater.bot


def success(result, err):
    print("success : ", result)
    print("success : ", err)


def failure(result, err):
    print("failure : ", result)


@dispatcher.command_handler("/start")
def start_command(bot, update):
    message = update.get_effective_message()
    bot.respond(update, message, success_callback=success, failure_callback=failure)


app = Flask(__name__)


class ServerActor(pykka.ThreadingActor):
    def __init__(self, flask_app):
        super(ServerActor, self).__init__()
        self.flask_app = flask_app

    def on_receive(self, message):
        print(message)

    def run(self):
        self.flask_app.run(host='0.0.0.0', port=5050)

    def shutdown_server(self):
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
            raise RuntimeError('Not running with the Werkzeug Server')
        func()


@app.route("/", methods=['GET'])
def send_to_user():
    message = "hello"
    m = TextMessage(message)
    bale_bot.send_message(m, Peer('User', "1533910422", "6644828719985087310"), success_callback=success,
                          failure_callback=failure)
    return "message sent"


# class SMStarter():
def start(notification_sender, server_actor_ref):
    server_proxy = server_actor_ref.proxy()
    future = server_proxy.run()
    notification_sender.run()
    notification_sender.stop()


start(notification_sender=updater, server_actor_ref=ServerActor.start(flask_app=app))

答案 1 :(得分:2)

通常,您有两个选择。首先,使用两个程序之间的共享数据库,一个程序获取请求并写入数据库,而另一个程序读取数据库并发送消息。 其次,如果您不想使用数据库,则可以在pykka中使用actor。它在Thread中实现actor并使用它们以在获取请求时发送消息。 这是一个很好的文档: https://www.pykka.org/en/latest/