Skip to content
This repository has been archived by the owner on Jun 4, 2022. It is now read-only.

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
runarsf committed May 9, 2020
1 parent c4fbed9 commit 83ef33d
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 41 deletions.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ services:
volumes:
- "./src:/app"
#- ./logs:/app/logs
network_mode: host
#ports:
#- 8080:8080
16 changes: 7 additions & 9 deletions src/cogs/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,11 +358,10 @@ async def _trump(self, ctx, *, searchString: str = 'random'):
async def _fox(self, ctx):
""" Send a picture of a random fox.
"""
#URL = 'https://api.runarsf.dev/floof?type=json'
URL = 'http://192.168.0.42/random?type=json&album=fox'
DATA = requests.get(URL, proxies={'no': 'pass',}).json()
OUT = DATA['url']
await ctx.send(OUT)
URL = 'https://floof.runarsf.dev/api/random?type=json&album=fox'
#DATA = requests.get(URL, proxies={'no': 'pass',}, verify=False).json()
DATA = requests.get(URL).json()
await ctx.send(DATA['url'])

@commands.command(name='floof')
async def _floof(self, ctx, album: str = ''):
Expand All @@ -371,10 +370,9 @@ async def _floof(self, ctx, album: str = ''):
#URL = 'https://api.runarsf.dev/floof?type=json'
if album:
album = f'&album={album}'
URL = f'http://192.168.0.42/random?type=json{album}'
DATA = requests.get(URL, proxies={'no': 'pass',}).json()
OUT = DATA['url']
await ctx.send(OUT)
URL = f'https://floof.runarsf.dev/api/random?type=json{album}'
DATA = requests.get(URL).json()
await ctx.send(DATA['url'])

@commands.command(name='query', aliases=['what', 'is', 'am'])
async def _query(self, ctx, *, searchString: str = ''):
Expand Down
73 changes: 41 additions & 32 deletions src/rufus.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import random
import datetime
import sqlite3
import logging
import discord
import config as c
import sys
Expand All @@ -27,25 +28,36 @@
'cogs.help'
]

def get_prefix(bot, message):
# FIXME: Check if this works
# DEBUG, INFO, WARNING, ERROR, CRITICAL, EXCEPTION
logging.basicConfig(stream=sys.stdout,
#filename='bot.log',
level=logging.INFO,
format='[%(asctime)s] [' + '%(levelname)s'.ljust(9) + '] %(name)s %(message)s',
datefmt='%d/%m/%Y %H:%M:%S'
)
log = logging.getLogger(__name__)

def get_prefix(_bot, message):
if not message.guild:
pass
return commands.when_mentioned_or(*c.prefixes)(bot, message)
return ''
return commands.when_mentioned_or(*c.prefixes)(_bot, message)

bot = commands.Bot(command_prefix=get_prefix, description=c.description)

@bot.event
async def on_ready():
# TODO: Find max lenght of string and create padding using ljust()
print('-' * len(str(bot.user.id)))
joined = []
for guild in bot.guilds:
joined.append(f' - {str(guild.name)} :: {str(guild.id)}')
print()
print('Logged in as:')
print(f'{bot.user.name} - {bot.user.id}')
print(f'Version: {discord.__version__}')
print(f'\nBot currently running on {len(bot.guilds)} servers:')
for s in bot.guilds:
print(f' - {str(s.name)} :: {str(s.id)}')
print('-' * len(str(bot.user.id))+'\n')
print(f'\nBot currently running on {len(bot.guilds)} server(s):')
print('-' * len(max(joined, key=len)))
print('\n'.join(joined))
print('-' * len(max(joined, key=len)))
print()

await bot.change_presence(status=discord.Status.online, activity=discord.Game(c.game))

Expand All @@ -57,7 +69,7 @@ async def on_message(message):
if str(rules.getrule('prefixless', message.guild.id)).lower() == 'true':
if re.compile(r'(\s+|^)(' + '|'.join(c.swears) + ')(\s+|$)').search(message.content.lower()):
await message.add_reaction(random.choice(c.rages))
logger(message)
log.info(message)
if message.content.startswith('man '):
message.content = message.content.replace('man ', c.prefixes[0]+'help ')
if message.content.upper() == 'F':
Expand All @@ -68,48 +80,45 @@ async def on_message(message):
if message.content.lower().startswith(dad):
if dad in message.content.lower():
await message.channel.send(random.choice(c.greetings)+', '+message.content[int(message.content.lower().find(dad))+len(dad):].strip()+'! I\'m Rufus.')
logger(message)
log.info(message)
except:
pass
for prefix in range(len(c.prefixes)):
if message.content.startswith(prefix):
logger(message)
await bot.process_commands(message)
log.info(message)
await bot.process_commands(message)

@bot.event
async def on_command_error(self, exception):
log.info(exception)
if isinstance(exception, commands.errors.MissingPermissions):
exception = f'Sorry {self.message.author.name}, you don\'t have permissions to do that!'
elif isinstance(exception, commands.errors.CheckFailure):
exception = f'Sorry {self.message.author.name}, you don\'t have the necessary roles for that!'
elif isinstance(exception, TimeoutError):
log.warn(f'TimeoutError: {exception}')
return
error_embed = discord.Embed(title='', timestamp=datetime.datetime.utcnow(), description=f'```python\n{exception}```', color=discord.Color.from_rgb(200, 0, 0))
error_embed.set_author(name=str(self.message.author), icon_url=str(self.message.guild.get_member(self.message.author.id).avatar_url))

error_embed = discord.Embed(title='',
timestamp=datetime.datetime.utcnow(),
description=f'```python\n{exception}```',
color=discord.Color.from_rgb(200, 0, 0))
error_embed.set_author(name='Woops!',
icon_url=str(self.message.author.avatar_url))
error_embed.set_footer(text=str(type(exception).__name__))
error_message = await self.send(embed=error_embed)

await errorMessage.add_reaction('❔')
await error_message.add_reaction('❔')

def check_reaction(reaction, user):
return user != self.bot.user and str(reaction.emoji) == '❔'
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=15.0, check=check_reaction)
except asyncio.TimeoutError:
await errorMessage.remove_reaction('❔', self.bot.user)
await error_message.remove_reaction('❔', self.bot.user)
else:
await errorMessage.remove_reaction('❔', self.bot.user)
errorEmbed.add_field(name='Details', value=f'{exception.__doc__}', inline=False)
errorEmbed.add_field(name='Cause', value=f'{exception.__cause__ }', inline=False)
await errorMessage.edit(embed=errorEmbed)
# await self.send('Unknown error: '+exception.__doc__)

def logger(message):
# TODO: Use an actual logger (logging)
try:
print(f'{message.author.name} {message.author.mention} :: {message.guild.name} :: {message.content}')
except:
print(f'{message.author.name} {message.author.mention} :: {message.content}')
await error_message.remove_reaction('❔', self.bot.user)
error_embed.add_field(name='Details', value=f'{exception.__doc__}', inline=False)
error_embed.add_field(name='Cause', value=f'{exception.__cause__ }', inline=False)
await error_message.edit(embed=error_embed)


if __name__ == '__main__':
Expand Down

0 comments on commit 83ef33d

Please sign in to comment.