Skip to content
This repository has been archived by the owner on Dec 22, 2023. It is now read-only.

Commit

Permalink
Merge pull request #12 from Bytespeicher/refactor-irc3
Browse files Browse the repository at this point in the history
Refactor irc3
  • Loading branch information
jurkov authored Nov 2, 2016
2 parents cf48a1d + 7be31d2 commit 217e1e7
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 25 deletions.
5 changes: 4 additions & 1 deletion bytebot_config.py.example
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ BYTEBOT_PLUGIN_CONFIG = {
'weather': {
'api_key': 'your_apikey',
'url': 'http://api.openweathermap.org/data/2.5/weather?units=metric&q=',
'location': 'Erfurt,de'
'location': 'city,countrycode'
},
'wikipedia': {
'url': 'https://de.wikipedia.org/w/api.php?&action=query&format=json&prop=extracts&exintro=&explaintext=&titles='
},
}
3 changes: 2 additions & 1 deletion lib/spaceapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
from irc3 import asyncio
from bytebot_config import BYTEBOT_PLUGIN_CONFIG


@asyncio.coroutine
def spaceapi(bot):
def spaceapi(bot, target):
with aiohttp.Timeout(10):
with aiohttp.ClientSession(loop=bot.loop) as session:
resp = yield from session.get(
Expand Down
42 changes: 21 additions & 21 deletions plugins/station.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
#!/usr/bin/env python3
#!python3
# -*- coding: utf-8 -*-
from irc3.plugins.command import command

from irc3.plugins.command import command

from bytebot_config import BYTEBOT_PLUGIN_CONFIG
from irc3 import asyncio
import json
import aiohttp
import datetime
import time


@command(permission="view")
@asyncio.coroutine
def station(bot, mask, target, args):
Expand All @@ -19,12 +15,12 @@ def station(bot, mask, target, args):
%%station
"""
url = "https://wla.31384.de:4044/evag/functions/departures"
payload = {"extId": "151213","useTimestamp": True}
payload = {"extId": "151213", "useTimestamp": True}
headers = {"Content-Type": "application/json"}
with aiohttp.Timeout(10):
with aiohttp.ClientSession(loop=bot.loop) as session:
resp = yield from session.post(url, data=json.dumps(payload),
headers=headers)
headers=headers)
if resp.status != 200:
bot.privmsg(target, "Error while retrieving traffic data.")
raise Exception()
Expand All @@ -35,31 +31,35 @@ def station(bot, mask, target, args):
departures = j["result"]["departures"]

data = []
count = 0;
count = 0

for i in range(len(departures)):
if(j["result"]["departures"][i]["timestamp"] >= time.time()):
data.append(
{'departure': j["result"]["departures"][i]["timestamp"],
'type': j["result"]["departures"][i]["type"],
'targetLocation': j["result"]["departures"][i]
["targetLocation"],
'targetLocation':
j["result"]["departures"][i]["targetLocation"],
'line': j["result"]["departures"][i]["line"]})
if(count>10):
if(count > 10):
break
else:
count = count + 1

bot.privmsg(target, "Erfurt, Leipziger Pl.");
bot.privmsg(target, "Erfurt, Leipziger Pl.")
for i in range(len(data)):
bot.privmsg(target,
"%s: %4.4s %s -> %s" % (datetime.datetime.fromtimestamp(
data[i]['departure']).strftime('%H:%M'),
data[i]['type'].upper(),
data[i]['line'],
data[i]['targetLocation'],
))

bot.privmsg(
target,
"%s: %4.4s %s -> %s" % (
datetime.datetime.fromtimestamp(
data[i]['departure']
).strftime('%H:%M'),
data[i]['type'].upper(),
data[i]['line'],
data[i]['targetLocation'],
)
)

except KeyError:
bot.privmsg(target, "Error while retrieving traffic data.")
raise Exception()
4 changes: 2 additions & 2 deletions plugins/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def status(bot, mask, target, args):
%%status
"""
try:
data = yield from spaceapi(bot)
data = yield from spaceapi(bot, target)

bot.privmsg(target, 'Space status:')
if data['state']['open']:
Expand All @@ -32,7 +32,7 @@ def users(bot, mask, target, args):
%%users
"""
try:
data = yield from spaceapi(bot)
data = yield from spaceapi(bot, target)
data = data['sensors']['people_now_present'][0]

if data['value'] > 0:
Expand Down
1 change: 1 addition & 0 deletions plugins/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import json
import aiohttp


@command(permission="view")
@asyncio.coroutine
def weather(bot, mask, target, args):
Expand Down
55 changes: 55 additions & 0 deletions plugins/wikipedia.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#!/usr/bin/env python2
# -*- coding: utf-8 -*-

from plugins.plugin import Plugin
from bytebot_config import BYTEBOT_PLUGIN_CONFIG
import requests
import urllib


class wikipedia(Plugin):
"""
With this plugin you can search for wikipedia entries.
"""
def __init__(self):
pass

def registerCommand(self, irc):
irc.registerCommand(
'!wiki TOPIC',
'wikipedia article summary for TOPIC'
)

def onPrivmsg(self, irc, msg, channel, user):
if msg.find('!wiki') == -1:
return

self.irc = irc
self.channel = channel

config = BYTEBOT_PLUGIN_CONFIG['wikipedia']

if msg.find(' ') == -1:
irc.msg(channel, 'usage: !wiki TOPIC')
return
else:
request = " ".join(msg.split(' ')[1:])

url = config['url'] + urllib.quote(request)

try:
r = requests.get(url)

if r.status_code != 200:
irc.msg(channel, 'Error while retrieving wikipedia data')
return

w = r.json()["query"]["pages"]
text = w[list(w.keys())[0]]["extract"][0:300]
text = text[0:text.rfind(" ")] + "[. . .]"

except KeyError:
irc.msg(channel, "Error while retrieving wikipedia data")
return

irc.msg(channel, "%s: %s" % (request, text))

0 comments on commit 217e1e7

Please sign in to comment.