Splitted up plugins, cosmetics for requires variables

This commit is contained in:
mrhanky 2017-05-18 02:01:44 +02:00
parent b0f36a1924
commit 04601fdf39
No known key found for this signature in database
GPG Key ID: 67D772C481CB41B8
13 changed files with 140 additions and 148 deletions

View File

@ -10,23 +10,21 @@
"flood_rate": 4,
"flood_rate_delay": 1,
"includes": [
"irc3.plugins.async",
"irc3.plugins.cron",
"irc3.plugins.command",
"irc3.plugins.uptime",
"nxy.plugins.admin",
"nxy.plugins.coins",
"nxy.plugins.bitcoin",
"nxy.plugins.ctcp",
"nxy.plugins.database",
"nxy.plugins.futures",
"nxy.plugins.mcmaniac",
"nxy.plugins.media",
"nxy.plugins.youtube",
"nxy.plugins.quotes",
"nxy.plugins.useless"
"nxy.plugins.tell",
"nxy.plugins.timer",
"nxy.plugins.useless",
"nxy.plugins.youtube"
],
"irc3.plugins.command": {
"cmd": ".",
"guard": "irc3.plugins.command.mask_based_policy"
"guard": "irc3.plugins.command.mask_based_policy",
"cmd": "."
},
"irc3.plugins.command.masks": {
"mrhanky!mrhanky@cocaine-import.agency": "all_permissions",

View File

@ -16,14 +16,14 @@ CFG_DEV = {
'raw': True,
'debug': True,
'verbose': True,
"irc3.plugins.command.masks": {
"*!admin@127.0.0.1": "all_permissions",
"*": "view"
'irc3.plugins.command.masks': {
'*!admin@127.0.0.1': 'all_permissions',
'*': 'view',
}
}
# TODO: imdb, youtube, pay, owe, rape (owe), ddg, regex, tell
# TODO: imdb, pay, owe, rape (owe), ddg, regex
def main(cfg_file):
load_dotenv('.env')
with open(cfg_file, 'r') as fp:

View File

@ -12,10 +12,8 @@ from ..utils import fmt
# noinspection PyUnusedLocal
@irc3.plugin
class Coins(Plugin):
requires = [
'irc3.plugins.command',
]
class Bitcoin(Plugin):
requires = ['irc3.plugins.command']
@command
def btc(self, mask: IrcString, channel: IrcString, args: DocOptDict):

View File

@ -13,12 +13,10 @@ from ..utils import fmt
# noinspection PyUnusedLocal
@irc3.plugin
class CTCP(Plugin):
TIMEOUT = 10
requires = ['irc3.plugins.async',
'irc3.plugins.command']
requires = [
'irc3.plugins.async',
'irc3.plugins.command',
]
TIMEOUT = 10
async def ctcp(self, ctcp: str, mask: IrcString, args: DocOptDict):
nick = args.get('<nick>') or mask.nick

View File

@ -8,10 +8,8 @@ from ..utils import parse_int
class McManiac(DatabasePlugin):
requires = [
'irc3.plugins.command',
'nxy.plugins.database',
]
requires = ['irc3.plugins.command',
'nxy.plugins.database']
# noinspection PyUnusedLocal
@command(options_first=True)

View File

@ -1,63 +0,0 @@
# -*- coding: utf-8 -*-
import irc3
import os
import re
import requests
from irc3 import event, IrcBot
from . import Plugin
from ..utils import fmt, date_from_iso
YOUTUBE_URL = 'https://www.googleapis.com/youtube/v3'
YOUTUBE_API = '{}/videos?part=snippet,statistics,contentDetails' \
.format(YOUTUBE_URL)
YOUTUBE_SEARCH = '{}/search?part=id,snippet'.format(YOUTUBE_URL)
@irc3.plugin
class Media(Plugin):
requires = [
'irc3.plugins.command',
]
def __init__(self, bot: IrcBot):
super().__init__(bot)
self.GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
@event(r'(?i)^:.* PRIVMSG (?P<target>.*) :.*(?:youtube.*?(?:v=|/v/)'
r'|youtu\.be/)(?P<video_id>[-_a-zA-Z0-9]+).*')
def youtube(self, target: str, video_id: str):
req = requests.get(YOUTUBE_API, params={
'key': self.GOOGLE_API_KEY,
'id': video_id})
data = req.json()
if not data['items']:
return
item = data['items'][0]
stats = item['statistics']
date = date_from_iso(item['snippet']['publishedAt'])
length = item['contentDetails']['duration']
length = re.findall('(\d+[DHMS])', length)
likes = int(stats.get('likeCount', 0))
dislikes = int(stats.get('dislikeCount', 0))
try:
score = 100 * float(likes) / (likes + dislikes)
except ZeroDivisionError:
score = 0
res = fmt('{title} - length {length} -{color}{green} {likes:,}{reset} '
'/{color}{maroon} {dislikes:,}{reset} ({score:,.1f}%) - '
'{views:,} views - {channel} on {date}',
title=item['snippet']['localized']['title'],
channel=item['snippet']['channelTitle'],
length=' '.join([l.lower() for l in length]),
date=date.strftime('%Y.%m.%d'),
views=int(stats.get('viewCount', 0)),
likes=likes,
dislikes=dislikes,
score=score)
self.bot.privmsg(target, res)

View File

@ -12,10 +12,8 @@ from ..utils import parse_int
@irc3.plugin
class Quotes(DatabasePlugin):
requires = [
'irc3.plugins.command',
'nxy.plugins.database',
]
requires = ['irc3.plugins.command',
'nxy.plugins.database']
NICK_REGEX = re.compile(r'<?[~&@%+]?([a-zA-Z0-9_\-^`|\\\[\]{}]+)>?')

53
nxy/plugins/tell.py Normal file
View File

@ -0,0 +1,53 @@
# -*- coding: utf-8 -*-
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
from irc3 import IrcBot, event
import irc3
from . import DatabasePlugin
@irc3.plugin
class Tell(DatabasePlugin):
requires = ['irc3.plugins.command',
'nxy.plugins.database']
def __init__(self, bot: IrcBot):
super().__init__(bot)
self.tell_queue = {}
# Restore tells from database
self.cur.execute('select from_user, to_user, message from tells')
for res in self.cur.fetchall():
user = res['to_user']
if user not in self.tell_queue:
self.tell_queue[user] = []
self.tell_queue[user].append(res)
# noinspection PyUnusedLocal
@command
def tell(self, mask: IrcString, channel: IrcString, args: DocOptDict):
"""Saves a message for nick to forward on activity
%%tell <nick> <message>...
"""
nick = args['<nick>'].lower()
if nick not in self.tell_queue:
self.tell_queue[nick] = []
tell = [mask.nick.lower(), nick, ' '.join(args['<message>'])]
self.tell_queue[nick].append(tell)
self.cur.execute('insert into tells (from_user, to_user, message)'
'values (?, ?, ?)', tell)
self.con.commit()
@event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*')
def check(self, mask: str):
"""If activ user has tells, forward and delete them."""
nick = IrcString(mask).nick
if nick in self.tell_queue:
for tell in self.tell_queue[nick]:
self.bot.privmsg(nick, '[Tell] Message from {nick}: {message}'
.format(nick=tell[0], message=tell[2]))
del self.tell_queue[nick]
self.cur.execute('delete from tells where to_user = ?', [nick])
self.con.commit()

View File

@ -5,7 +5,6 @@ import asyncio
from docopt import Dict as DocOptDict
from irc3.plugins.command import command
from irc3.utils import IrcString
from irc3 import IrcBot, event
import irc3
from . import DatabasePlugin
@ -13,15 +12,12 @@ from ..utils import fmt, time_delta
@irc3.plugin
class Futures(DatabasePlugin):
requires = [
'irc3.plugins.command',
'nxy.plugins.database',
]
class Timer(DatabasePlugin):
requires = ['irc3.plugins.command',
'nxy.plugins.database']
def __init__(self, bot: IrcBot):
def __init__(self, bot: irc3.IrcBot):
super().__init__(bot)
self.tell_queue = {}
# Restore timers from database
self.cur.execute('select id, mask, channel, message, delay, until '
'from timers')
@ -30,26 +26,6 @@ class Futures(DatabasePlugin):
args = (IrcString(res['mask']), res['channel'], delta,
res['message'], res['delay'], res['id'])
asyncio.ensure_future(self._timer(*args))
# Restore tells from database
self.cur.execute('select mask, user, message from tells')
for res in self.cur.fetchall():
user = res['user']
if user not in self.tell_queue:
self.tell_queue[user] = []
self.tell_queue[user].append(res)
@event(r'(?i)^:(?P<mask>.*) PRIVMSG .* :.*')
def tell_check(self, mask: str):
"""If activ user has tells, forward and delete them."""
nick = IrcString(mask).nick
if nick in self.tell_queue:
for tell in self.tell_queue[nick]:
self.bot.privmsg(nick, '[Tell] Message from {nick}: {message}'
.format(nick=IrcString(tell['mask']).nick,
message=tell['message']))
del self.tell_queue[nick]
self.cur.execute('delete from tells where user = ?', [nick])
self.con.commit()
@command
def timer(self, mask: IrcString, channel: IrcString, args: DocOptDict):
@ -73,26 +49,6 @@ class Futures(DatabasePlugin):
else:
self.bot.privmsg(channel, 'Invalid timer delay')
# noinspection PyUnusedLocal
@command
def tell(self, mask: IrcString, channel: IrcString, args: DocOptDict):
"""Saves a message for nick to forward on activity
%%tell <nick> <message>...
"""
nick = args['<nick>']
message = ' '.join(args['<message>'])
if nick not in self.tell_queue:
self.tell_queue[nick] = []
self.tell_queue[nick].append({
'mask': mask,
'user': nick,
'message': message,
})
self.cur.execute('insert into tells (mask, user, message) values '
'(?, ?, ?)', [mask, nick, message])
self.con.commit()
async def _timer(self, mask: IrcString, channel: IrcString,
delta: timedelta, message: str, delay: str, row_id: int):
"""Async function, sleeps for `delay` seconds and sends notification"""

View File

@ -25,9 +25,7 @@ GNU_LINUX = """I'd Just Like To Interject For A Moment. What you're referring
# noinspection PyUnusedLocal
@irc3.plugin
class Useless(Plugin):
requires = [
'irc3.plugins.command',
]
requires = ['irc3.plugins.command']
@event(r'(?i)^:.* PRIVMSG (?P<channel>.*) :'
r'.*(?<!gnu[/+])linux(?! kernel).*')

59
nxy/plugins/youtube.py Normal file
View File

@ -0,0 +1,59 @@
# -*- coding: utf-8 -*-
import irc3
import os
import re
import requests
from irc3 import event, IrcBot
from . import Plugin
from ..utils import fmt, date_from_iso
@irc3.plugin
class YouTube(Plugin):
requires = ['irc3.plugins.command']
URL = 'https://www.googleapis.com/youtube/v3'
API = '{}/videos?part=snippet,statistics,contentDetails'.format(URL)
SEARCH = '{}/search?part=id,snippet'.format(URL)
def __init__(self, bot: IrcBot):
super().__init__(bot)
self.GOOGLE_API_KEY = os.environ['GOOGLE_API_KEY']
@event(r'(?i)^:.* PRIVMSG (?P<target>.*) :.*(?:youtube.*?(?:v=|/v/)'
r'|youtu\.be/)(?P<video_id>[-_a-zA-Z0-9]+).*')
def youtube_parser(self, target: str, video_id: str):
req = requests.get(self.API, params={
'key': self.GOOGLE_API_KEY,
'id': video_id})
data = req.json()
if not data['items']:
return
item = data['items'][0]
date = date_from_iso(item['snippet']['publishedAt'])
length = item['contentDetails']['duration']
length = re.findall('(\d+[DHMS])', length)
likes = int(item['statistics'].get('likeCount', 0))
dislikes = int(item['statistics'].get('dislikeCount', 0))
try:
score = 100 * float(likes) / (likes + dislikes)
except ZeroDivisionError:
score = 0
text = fmt('{title} - length {length} -{color}{green} {likes:,}{reset}'
' /{color}{maroon} {dislikes:,}{reset} ({score:,.1f}%) - '
'{views:,} views - {channel} on {date}',
title=item['snippet']['localized']['title'],
channel=item['snippet']['channelTitle'],
length=' '.join([l.lower() for l in length]),
date=date.strftime('%Y.%m.%d'),
views=int(item['statistics'].get('viewCount', 0)),
likes=likes,
dislikes=dislikes,
score=score)
self.bot.privmsg(target, text)

View File

@ -5,7 +5,6 @@ import os
import re
from pprint import pprint
# noinspection PyPackageRequirements
from dotenv import load_dotenv
pp = pprint

View File

@ -23,8 +23,8 @@ create table if not exists timers (
create table if not exists tells (
id integer primary key autoincrement,
mask text not null,
user text not null,
from_user text not null,
to_user text not null,
message text not null,
created timestamp not null default current_timestamp
);