Skip to content

Conversation

@filippog
Copy link

mainly for convenience, it'd probably better to make it officially part of the
API

mainly for convenience, it'd probably better to make it officially part of the
API
@miohtama
Copy link
Member

Hi @filippog

Just to mention - this is on my todo list - have not had time to maintain the project for a while, but should change soon

@filippog
Copy link
Author

thanks Mikko! FYI, I've spent some time around a simple API for sending messages to chats (and supporting chat aliases via configuration). I'm dropping the code here in case you are interested:

import sys
import logging
import os

from flask import Flask, request, abort, jsonify, current_app, json


app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('SETTINGS')

CHAT_ALIAS = app.config.get('CHAT_ALIAS', {})


def get_bot():
    top = current_app
    if not hasattr(top, 'bot'):
        from sevabot.bot.bot import Sevabot
        top.bot = Sevabot()
    return top.bot


@app.before_first_request
def start_bot():
    with app.app_context():
        from sevabot.bot import modules

        sevabot = get_bot()
        sevabot.start()
        modules.load_modules(sevabot)
        app.logger.info("sevabot started")


def find_chat_id(chat_id):
    known_chats = chat_map()
    if chat_id in known_chats:
        return chat_id

    # reverse id -> name map, don't care about chat name collisions
    chat_names = dict([(name, id) for id in known_chats for name in
        known_chats[id]['name']])

    chat_alias = dict([(name, id) for id in known_chats for name in
        known_chats[id].get('alias', [])])

    chat_names.update(chat_alias)

    if chat_id in chat_names:
        return chat_names.get(chat_id)
    return None


def chat_map():
    res = {}
    for id, chat in get_bot().getOpenChats():
        res.setdefault(id, {}).update({'name': [chat.FriendlyName]})

    for id, alias in CHAT_ALIAS.iteritems():
        if id not in res:
            continue

        alias_list = res[id].setdefault('alias', [])
        if isinstance(alias, list):
            alias_list.extend(alias)
        else:
            alias_list.append(alias)


    return res


@app.route("/send/<string:chat>", methods=["POST"])
def list_chats(chat):
    """Send a message to chat, the name can be anything from GET /send.

    The body can be a JSON object or a form urlencoded, in both cases the
    message must be the 'msg' attribute/key."""

    sevabot = get_bot()
    chat_id = find_chat_id(chat)
    if chat_id is None:
        abort(404, "chat %s not found" % repr(chat))

    if request.json is not None and 'msg' in request.json:
        msg = request.json['msg']
    elif 'msg' in request.form:
        msg = request.form['msg']
    else:
        return abort(400, "can't find the message to send")

    sevabot.sendMessage(chat_id, msg)
    return jsonify({'result': 'ok', 'error': None})


@app.route("/send", methods=["GET"])
def send_message():
    """Return a json list of all known chats."""
    return jsonify(chat_map())


def main():
    app.run(port=app.config.get('HTTP_PORT', 5000))


if __name__ == '__main__':
    sys.exit(main())

adrianlzt added a commit to adrianlzt/sevabot that referenced this pull request Oct 22, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants