Skip to content

Commit 92eda5e

Browse files
committed
Got successful logging using webhooks and logging library
1 parent ff94a61 commit 92eda5e

File tree

9 files changed

+89
-56
lines changed

9 files changed

+89
-56
lines changed

.env-example

+2
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@ DISCORD_SERVER_CHANNEL_ID=
33
BOT_PREFIX_CHARACTER=
44
RECAPTCHA_PUBLIC_KEY=
55
RECAPTCHA_PRIVATE_KEY=
6+
LOGGING_WEBHOOK_CHANNEL=
7+
LOGGING_WEBHOOK_TOKEN=

JHDBot/bot.py

+21-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import os
77
import random
88
import helpembed
9+
import logging
10+
from webhook_logging.discordHook import DiscordHandler
911
#import configfile
1012

1113
load_dotenv()
@@ -216,8 +218,22 @@ async def attach_embed_info(ctx=None, embed=None):
216218
embed.set_footer(text='by: JHD Moderation team ')
217219
return embed
218220

219-
# Token
220-
TOKEN = os.getenv("DISCORD_API_TOKEN")
221-
bot.run(TOKEN) # token
222-
print("Bot started press ctrl+c to exit....")
223-
#bot.run(configfile.bot_token)
221+
if __name__ == '__main__':
222+
logger = logging.getLogger('Bot')
223+
logger.setLevel(logging.INFO)
224+
225+
hookToken = os.getenv("LOGGING_WEBHOOK_TOKEN")
226+
hookChannel = os.getenv("LOGGING_WEBHOOK_CHANNEL")
227+
discordHandler = DiscordHandler(f'https://discordapp.com/api/webhooks/{hookChannel}/{hookToken}')
228+
discordHandler.setLevel(logging.INFO)
229+
230+
formatter = logging.Formatter('[%(name)s] (%(levelname)s): %(message)s')
231+
discordHandler.setFormatter(formatter)
232+
233+
logger.addHandler(discordHandler)
234+
235+
logger.info("Bot Started")
236+
237+
TOKEN = os.getenv("DISCORD_API_TOKEN")
238+
239+
bot.run(TOKEN) # token

discord-webhooks/discord-webhooks/webhook.py

-33
This file was deleted.

discord-webhooks/setup.py

-16
This file was deleted.

docker-compose.yml

+6
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ services:
1919
environment:
2020
- DISCORD_API_TOKEN=${DISCORD_API_TOKEN}
2121
- BOT_PREFIX_CHARACTER=${BOT_PREFIX_CHARACTER}
22+
- LOGGING_WEBHOOK_CHANNEL=${LOGGING_WEBHOOK_CHANNEL}
23+
- LOGGING_WEBHOOK_TOKEN=${LOGGING_WEBHOOK_TOKEN}
2224

2325
webapp1:
2426
build: verify-web/.
@@ -29,6 +31,8 @@ services:
2931
- RECAPTCHA_PRIVATE_KEY=${RECAPTCHA_PRIVATE_KEY}
3032
- DISCORD_API_TOKEN=${DISCORD_API_TOKEN}
3133
- DISCORD_SERVER_CHANNEL_ID=${DISCORD_SERVER_CHANNEL_ID}
34+
- LOGGING_WEBHOOK_CHANNEL=${LOGGING_WEBHOOK_CHANNEL}
35+
- LOGGING_WEBHOOK_TOKEN=${LOGGING_WEBHOOK_TOKEN}
3236

3337
webapp2:
3438
build: verify-web/.
@@ -39,3 +43,5 @@ services:
3943
- RECAPTCHA_PRIVATE_KEY=${RECAPTCHA_PRIVATE_KEY}
4044
- DISCORD_API_TOKEN=${DISCORD_API_TOKEN}
4145
- DISCORD_SERVER_CHANNEL_ID=${DISCORD_SERVER_CHANNEL_ID}
46+
- LOGGING_WEBHOOK_CHANNEL=${LOGGING_WEBHOOK_CHANNEL}
47+
- LOGGING_WEBHOOK_TOKEN=${LOGGING_WEBHOOK_TOKEN}

discord-webhooks/README.md webhook_logging/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,5 +9,5 @@ Will eventually get uploaded to pypi but as of now requires a local install.
99

1010
Use:
1111
```python
12-
import discord-webhooks
12+
import discord-logging
1313
```

webhook_logging/setup.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#!/usr/bin/env python3
2+
from setuptools import setup
3+
4+
setup(
5+
name='webhook_logging',
6+
version='0.0.4',
7+
description='Simple library for sending logs from python logging to webhooks',
8+
url='https:/github.com/fumenoid/JHDBot/tree/webhook_logging/webhook_logging',
9+
author='JHD dev team',
10+
author_email='[email protected]',
11+
packages=['webhook_logging'],
12+
install_requires=[
13+
'requests',
14+
],
15+
classifiers=[],
16+
)

discord-webhooks/discord-webhooks/__init__.py webhook_logging/webhook_logging/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,5 @@
44
Simple library to send discord webhooks
55
'''
66

7-
__version__ = '0.0.1'
7+
__version__ = '0.0.3'
88
__author__ = 'JHD Dev Team'
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#!/usr/bin/env python3
2+
import logging
3+
import requests
4+
import json
5+
6+
7+
class DiscordHandler(logging.Handler):
8+
'''
9+
Class for sending logging records to discord webhooks.
10+
'''
11+
def __init__(self, url: str) -> None:
12+
"""
13+
Override the constructor because all of those stupid parameters aren't needed.
14+
"""
15+
logging.Handler.__init__(self)
16+
17+
self.url = url
18+
self.__testConnection(url)
19+
20+
def __testConnection(self, url: str) -> None:
21+
r = requests.get(url)
22+
if r.status_code != 200:
23+
raise Exception(f"Could not establish connection for webhook logging. URL returned a {r.status_code}")
24+
return
25+
26+
def mapLogRecord(self, record):
27+
return self.format(record)
28+
29+
def emit(self, record):
30+
"""
31+
Emit a record.
32+
33+
Send the record to the Web server as a percent-encoded dictionary
34+
"""
35+
try:
36+
url = self.url
37+
logMsg = self.mapLogRecord(record)
38+
data = json.dumps({"content": str(logMsg)})
39+
headers = {"content-type": "application/json"}
40+
r = requests.post(url, headers=headers, data=data)
41+
except Exception:
42+
self.handleError(record)

0 commit comments

Comments
 (0)