Skip to content

Commit 27124cb

Browse files
committed
Add logging
1 parent ca265c8 commit 27124cb

File tree

2 files changed

+30
-20
lines changed

2 files changed

+30
-20
lines changed

.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
1-
21
.env
3-
err.log
2+
logs/

protobot.py

Lines changed: 29 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,22 +12,42 @@
1212
from dotenv import load_dotenv #
1313
import random #
1414
from discord.ext import commands #
15+
import logging #
16+
import time #
1517
#
1618
#####################################
1719

20+
1821
#####################################
1922
#
2023
COMMAND_PREFIX = '!' #
2124
VERSION = "v0.1-alpha" #
2225
ACTIVITY = discord.Game("!help") #
26+
LOG_LEVEL = logging.INFO #
2327
#
2428
#####################################
2529

30+
31+
# Load bot token from .env
2632
load_dotenv()
2733
TOKEN = os.getenv('DISCORD_TOKEN')
2834

29-
bot = commands.Bot(command_prefix=COMMAND_PREFIX)
35+
# Initialize bot object to use the COMMAND_PREFIX defined above
36+
bot = commands.Bot(command_prefix=COMMAND_PREFIX)
37+
38+
# Generate timestamp of startup
39+
timestamp = time.strftime('%Y%m%d-%H%M%S')
3040

41+
# Configure logging
42+
logging.basicConfig(
43+
level = LOG_LEVEL,
44+
format = '%(asctime)s: [%(levelname)s] - %(message)s',
45+
datefmt = '%Y-%m-%d %H:%M:%S',
46+
handlers = [
47+
logging.FileHandler(f"logs/{timestamp}.log", mode = "w"),
48+
logging.StreamHandler()
49+
]
50+
)
3151

3252
@bot.event
3353
async def on_connect():
@@ -36,7 +56,7 @@ async def on_connect():
3656
Sets the bot activity to ACTIVITY.
3757
"""
3858

39-
print(f'{bot.user.name} {VERSION} has sucessfully connected to Discord.')
59+
logging.warning(f'{bot.user.name} {VERSION} has sucessfully connected to Discord.')
4060
await bot.change_presence(activity = ACTIVITY)
4161

4262

@@ -47,14 +67,11 @@ async def on_ready():
4767
date from Discord servers.
4868
"""
4969

50-
print('Bot loading complete. Current guilds: ', end='')
70+
logging.info('Bot loading complete. Current guilds: ')
5171

52-
guilds = []
5372
for guild in bot.guilds:
5473
label = guild.name + " (" + str(guild.id) + ")"
55-
guilds.append(label)
56-
57-
print(*guilds, sep=', ')
74+
logging.info(label)
5875

5976

6077
@bot.event
@@ -63,7 +80,7 @@ async def on_disconnect():
6380
Prints a message when bot disconnects from Discord. Usually this is temporary.
6481
"""
6582

66-
print('Lost connection to Discord.')
83+
logging.warning('Lost connection to Discord.')
6784

6885

6986

@@ -88,11 +105,10 @@ async def on_error(event, *args, **kwargs):
88105
Writes to err.log whenever a message triggers an error
89106
"""
90107

91-
with open('err.log', 'a', encoding='utf-8') as errfile:
92-
if event == 'on_message':
93-
errfile.write(f'Unhandled message: {args[0]}\n')
94-
else:
95-
raise
108+
if event == 'on_message':
109+
logging.error(f'Unhandled message: {args[0]}')
110+
else:
111+
logging.exception(event)
96112

97113

98114
@bot.event
@@ -114,7 +130,6 @@ async def on_message(message):
114130
Lets the bot say happy birthday whenever a user says it
115131
"""
116132

117-
print("Wishing someone a happy birthday!")
118133
await message.channel.send('Happy Birthday! 🎈🎉🎂')
119134

120135
await bot.process_commands(message)
@@ -132,15 +147,11 @@ async def on_message(message):
132147
for i in range(len(user_message)):
133148
if (' ' + user_message[i].lower() in ways_to_say_i_am):
134149

135-
print("Dad joke incoming!")
136-
137150
if len(user_message) - i < 2:
138-
print("False alarm, user message too short!")
139151
break
140152

141153
else:
142154
response = "Hi " + " ".join(user_message[i + 1:]) + "! I'm dad!"
143-
print(response)
144155
await message.channel.send(response)
145156
break
146157

0 commit comments

Comments
 (0)