allow /chats/ to return JSON #45
Open
filippog wants to merge 1 commit intoopensourcehacker:masterfrom
filippog:master
Open
allow /chats/ to return JSON #45filippog wants to merge 1 commit intoopensourcehacker:masterfrom filippog:master
filippog wants to merge 1 commit intoopensourcehacker:masterfrom
filippog:master
Conversation
mainly for convenience, it'd probably better to make it officially part of the API
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 |
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
mainly for convenience, it'd probably better to make it officially part of the
API