Reputation: 3519
I'm starting with Python and I'm currently working on a Discord bot with the API. So far so good, everything works. Now, I'm looking to host the script on a server without the console, which means I want the output to go in a file instead of in the console. I have the following currently working:
import discord
import logging
logging.basicConfig(filename='.\output.log', filemode='w', level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s')
xzbot = discord.Client()
# logging when the bot starts
@xzbot.event
async def on_ready():
logging.info('Logged in as ' + xzbot.user.name + ' (' + xzbot.user.id + ')\n')
So this code will put any warnings and infos in output.log. With that said, it doesn't work with exceptions raised by the Discord.py such as "Permissions denied" when the bot is trying to send a message without having the permissions.
There is a built-in function in the Discord API to handle that:
discord.on_error(event, *args, **kwargs)
So I can call this function this way:
async def xzbot.on_error(event, *args, **kwargs):
pass
Now, I tried doing something with event
, *args
or **kwargs
but I need some help here to get that in a format where I can just use logging.warning()
. All I'm able to get is object
as a result of a print(*args)
and I don't know how to format that properly.
Upvotes: 0
Views: 12133
Reputation: 90
Okay, so this snippet of code will log, and also send a message to the channel where the error was caused.
You can remove the await xzbot.send_message
if you wouldn't like it to send a message.
import traceback
@xzbot.event
async def on_error(event, *args, **kwargs):
message = args[0] #Gets the message object
logging.warning(traceback.format_exc()) #logs the error
await xzbot.send_message(message.channel, "You caused an error!") #send the message to the channel
traceback.format_exc() formats the last error, so it will look like a normal error that is printed to the console.
Here's info on the traceback module.
Upvotes: 5