1
0
Fork 0
mirror of synced 2024-06-28 03:00:55 +12:00
This commit is contained in:
phxntxm 2016-08-12 00:17:47 -05:00
commit 276d35213f
7 changed files with 67 additions and 36 deletions

1
.gitignore vendored
View file

@ -10,3 +10,4 @@ autoupdate.php
error_log error_log
images/* images/*
.ftpquota .ftpquota
bonfire.log

5
bot.py
View file

@ -5,6 +5,8 @@ import traceback
import logging import logging
import datetime import datetime
import pendulum import pendulum
import os
from discord.ext import commands from discord.ext import commands
from cogs.utils import config from cogs.utils import config
@ -25,6 +27,7 @@ extensions = ['cogs.interaction',
bot = commands.Bot(command_prefix=config.commandPrefix, description=config.botDescription, pm_help=None) bot = commands.Bot(command_prefix=config.commandPrefix, description=config.botDescription, pm_help=None)
discord_logger = logging.getLogger('discord') discord_logger = logging.getLogger('discord')
discord_logger.setLevel(logging.WARNING) discord_logger.setLevel(logging.WARNING)
os.chdir(os.path.dirname(os.path.realpath(__file__)))
log = logging.getLogger() log = logging.getLogger()
log.setLevel(logging.INFO) log.setLevel(logging.INFO)
@ -101,7 +104,7 @@ async def on_command_error(error, ctx):
await bot.send_message(ctx.message.channel, error) await bot.send_message(ctx.message.channel, error)
elif not isinstance(error, commands.CommandNotFound): elif not isinstance(error, commands.CommandNotFound):
now = datetime.datetime.now() now = datetime.datetime.now()
with open("{}/error_log".format(config.base_path), 'a') as f: with open("error_log", 'a') as f:
print("In server '{0.message.server}' at {1}\nFull command: `{0.message.content}`".format(ctx, str(now)), print("In server '{0.message.server}' at {1}\nFull command: `{0.message.content}`".format(ctx, str(now)),
file=f) file=f)
try: try:

View file

@ -77,8 +77,7 @@ class Core:
async def doggo(self, ctx): async def doggo(self, ctx):
"""Use this to print a random doggo image. """Use this to print a random doggo image.
Doggo is love, doggo is life.""" Doggo is love, doggo is life."""
os.chdir('/home/phxntx5/public_html/Bonfire/images') f = glob.glob('images/doggo*')[random.randint(0, len(glob.glob('doggo*')) - 1)]
f = glob.glob('doggo*')[random.randint(0, len(glob.glob('doggo*')) - 1)]
with open(f, 'rb') as f: with open(f, 'rb') as f:
await self.bot.upload(f) await self.bot.upload(f)
@ -87,8 +86,7 @@ class Core:
async def snek(self, ctx): async def snek(self, ctx):
"""Use this to print a random snek image. """Use this to print a random snek image.
Sneks are o3o""" Sneks are o3o"""
os.chdir('/home/phxntx5/public_html/Bonfire/images') f = glob.glob('images/snek*')[random.randint(0, len(glob.glob('snek*')) - 1)]
f = glob.glob('snek*')[random.randint(0, len(glob.glob('snek*')) - 1)]
with open(f, 'rb') as f: with open(f, 'rb') as f:
await self.bot.upload(f) await self.bot.upload(f)

View file

@ -12,6 +12,17 @@ class Mod:
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@commands.command(pass_context=True, no_pm=True)
@checks.customPermsOrRole(kick_members=True)
async def alerts(self, ctx, channel: discord.Channel):
"""This command is used to set a channel as the server's 'notifications' channel
Any notifications (like someone going live on Twitch, or Picarto) will go to that channel"""
server_alerts = config.getContent('server_alerts') or {}
server_alerts[ctx.message.server.id] = channel.id
await self.bot.say("I have just changed this server's 'notifications' channel"
"\nAll notifications will now go to `{}`".format(channel))
@commands.command(pass_context=True, no_pm=True) @commands.command(pass_context=True, no_pm=True)
@checks.customPermsOrRole(kick_members=True) @checks.customPermsOrRole(kick_members=True)
async def usernotify(self, ctx, on_off:str): async def usernotify(self, ctx, on_off:str):
@ -22,7 +33,7 @@ class Mod:
notifications = config.getContent('user_notifications') or {} notifications = config.getContent('user_notifications') or {}
notifications[ctx.message.server.id] = on_off notifications[ctx.message.server.id] = on_off
config.saveContent('user_notifications',notifications) config.saveContent('user_notifications',notifications)
fmt = "notify, in this channel" if on_off else "not notify" fmt = "notify" if on_off else "not notify"
await self.bot.say("This server will now {} if someone has joined or left".format(fmt)) await self.bot.say("This server will now {} if someone has joined or left".format(fmt))
@commands.group(pass_context=True, no_pm=True) @commands.group(pass_context=True, no_pm=True)

View file

@ -32,8 +32,7 @@ class Owner:
@commands.check(checks.isOwner) @commands.check(checks.isOwner)
async def adddoggo(self, url: str): async def adddoggo(self, url: str):
"""Saves a URL as an image to add for the doggo command""" """Saves a URL as an image to add for the doggo command"""
os.chdir('{}/images'.format(config.base_path)) local_path = 'images/doggo{}.jpg'.format(len(glob.glob('doggo*')))
local_path = 'doggo{}.jpg'.format(len(glob.glob('doggo*')))
with aiohttp.ClientSession() as s: with aiohttp.ClientSession() as s:
async with s.get(url) as r: async with s.get(url) as r:
val = await r.read() val = await r.read()
@ -46,8 +45,7 @@ class Owner:
@commands.check(checks.isOwner) @commands.check(checks.isOwner)
async def addsnek(self, url: str): async def addsnek(self, url: str):
"""Saves a URL as an image to add for the snek command""" """Saves a URL as an image to add for the snek command"""
os.chdir('{}/images'.format(config.base_path)) local_path = 'images/snek{}.jpg'.format(len(glob.glob('snek*')))
local_path = 'snek{}.jpg'.format(len(glob.glob('snek*')))
with aiohttp.ClientSession() as s: with aiohttp.ClientSession() as s:
async with s.get(url) as r: async with s.get(url) as r:
val = await r.read() val = await r.read()
@ -90,7 +88,7 @@ class Owner:
@commands.check(checks.isOwner) @commands.check(checks.isOwner)
async def avatar(self, content: str): async def avatar(self, content: str):
"""Changes the avatar for the bot to the filename following the command""" """Changes the avatar for the bot to the filename following the command"""
file = '{}/images/{}'.format(config.base_path, content) file = 'images/' + content
with open(file, 'rb') as fp: with open(file, 'rb') as fp:
await self.bot.edit_profile(avatar=fp.read()) await self.bot.edit_profile(avatar=fp.read())

View file

@ -14,16 +14,19 @@ base_url = 'https://ptvappapi.picarto.tv'
key = '03e26294-b793-11e5-9a41-005056984bd4' key = '03e26294-b793-11e5-9a41-005056984bd4'
async def check_online(stream): async def online_users():
try: try:
url = '{}/channel/{}?key={}'.format(base_url, stream, key) url = '{}/online/all?key={}'.format(base_url, key)
with aiohttp.ClientSession(headers={"User-Agent": "Bonfire/1.0.0"}) as s: with aiohttp.ClientSession(headers={"User-Agent": "Bonfire/1.0.0"}) as s:
async with s.get(url) as r: async with s.get(url) as r:
response = await r.text() response = await r.text()
return json.loads(response).get('is_online') return json.loads(response)
except: except:
return False return {}
def check_online(online_channels, channel):
matches = [stream for stream in online_channels if stream['channel_name'].lower() == channel.lower()]
return len(matches) > 0
class Picarto: class Picarto:
def __init__(self, bot): def __init__(self, bot):
@ -33,16 +36,19 @@ class Picarto:
await self.bot.wait_until_ready() await self.bot.wait_until_ready()
while not self.bot.is_closed: while not self.bot.is_closed:
picarto = config.getContent('picarto') or {} picarto = config.getContent('picarto') or {}
online_users = await online_users()
for m_id, r in picarto.items(): for m_id, r in picarto.items():
url = r['picarto_url'] url = r['picarto_url']
live = r['live'] live = r['live']
notify = r['notifications_on'] notify = r['notifications_on']
user = re.search("(?<=picarto.tv/)(.*)", url).group(1) user = re.search("(?<=picarto.tv/)(.*)", url).group(1)
online = await check_online(user) online = check_online(online_users, user)
if not live and notify and online: if not live and notify and online:
for server_id, channel_id in r['servers'].items(): for server_id in r['servers'].items():
server = self.bot.get_server(server_id) server = self.bot.get_server(server_id)
server_alerts = config.getContent('server_alerts') or {}
channel_id = server_alerts.get(server_id) or server_id
channel = self.bot.get_channel(channel_id) channel = self.bot.get_channel(channel_id)
member = discord.utils.find(lambda m: m.id == m_id, server.members) member = discord.utils.find(lambda m: m.id == m_id, server.members)
@ -53,6 +59,8 @@ class Picarto:
elif live and not online: elif live and not online:
for server_id, channel_id in r['servers'].items(): for server_id, channel_id in r['servers'].items():
server = self.bot.get_server(server_id) server = self.bot.get_server(server_id)
server_alerts = config.getContent('server_alerts') or {}
channel_id = server_alerts.get(server_id) or server_id
channel = self.bot.get_channel(channel_id) channel = self.bot.get_channel(channel_id)
member = discord.utils.find(lambda m: m.id == m_id, server.members) member = discord.utils.find(lambda m: m.id == m_id, server.members)

View file

@ -3,40 +3,52 @@ import asyncio
import json import json
loop = asyncio.get_event_loop() loop = asyncio.get_event_loop()
base_path = "/home/phxntx5/public_html/Bonfire"
with open("{}/config.yml".format(base_path), "r") as f:
global_config = yaml.load(f)
connection = None try:
with open("config.yml", "r") as f:
global_config = yaml.load(f)
except FileNotFoundError:
print("You have no config file setup! Please use config.yml.sample to setup a valid config file")
quit()
botDescription = global_config.get("description") botDescription = global_config.get("description")
commandPrefix = global_config.get("command_prefix", "!") commandPrefix = global_config.get("command_prefix", "!")
discord_bots_key = global_config.get('discord_bots_key') discord_bots_key = global_config.get('discord_bots_key', "")
battleWins = global_config.get("battleWins", []) battleWins = global_config.get("battleWins", [])
defaultStatus = global_config.get("default_status", "") defaultStatus = global_config.get("default_status", "")
botToken = global_config.get("bot_token", "") try:
owner_ids = global_config.get("owner_id", []) botToken = global_config["bot_token"]
except KeyError:
print("You have no bot_token saved, this is a requirement for running a bot.")
print("Please use config.yml.sample to setup a valid config file")
quit()
try:
owner_ids = global_config["owner_id"]
except KeyError:
print("You have no owner_id saved! You're not going to be able to run certain commands without this.")
print("Please use config.yml.sample to setup a valid config file")
quit()
def saveContent(key: str, content): def saveContent(key: str, content):
with open("{}/config.json".format(base_path), "r+") as jf: with open("config.json", "a+") as jf:
data = json.load(jf)
jf.seek(0)
data[key] = content
try: try:
json.dumps(data) data = json.load(jf)
except: except json.JSONDecodeError:
return False data = {}
else: data[key] = content
jf.truncate() jf.seek(0)
json.dump(data, jf, indent=4) jf.truncate()
return True json.dump(data, jf, indent=4)
def getContent(key: str): def getContent(key: str):
try: try:
with open("{}/config.json".format(base_path), "r+") as jf: with open("config.json", "r+") as jf:
return json.load(jf)[key] return json.load(jf)[key]
except KeyError: except KeyError:
return None return None
except FileNotFoundError:
return None