Skip to content

Commit

Permalink
New config options & handling improvements (#18)
Browse files Browse the repository at this point in the history
* New config options & loading improvements

* Change to minor release

* Fix YAML errors

* Update linting.yml

* Update linting.yml

* Update linting.yml

* Update requirements.txt

* Update pyproject.toml
  • Loading branch information
finlaysawyer committed Feb 19, 2021
1 parent 4eeb5b2 commit 4661687
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 26 deletions.
23 changes: 15 additions & 8 deletions .github/workflows/linting.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,20 @@ jobs:
with:
python-version: 3.7

- name: Install Python tools
run: pip install pylint black bandit

- name: Install Python dependencies
run: pip install black flake8
run: pip install -r requirements.txt

- name: Run linters
uses: wearerequired/lint-action@v1
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
black: true
flake8: true
auto_fix: true
- name: Run pylint
run: |
pylint bot.py
pylint cogs
pylint utils
- name: Run black
run: black --verbose --check --diff .

- name: Run bandit
run: bandit -r .
16 changes: 15 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
# Changelog

## [1.1.0] - 2021-02-19

### Added
- Bandit for security linting
- User-friendly errors when a config is formatted incorrectly or missing values
- Configurable bot status in `config.json`:
- `activity_type` - one of `playing, streaming, listening, watching`
- `activity_name` - any string
- Default help command can now be disabled by setting `disable_help` to 'true'

### Changed
- Replaced flake8 with pylint and did some minor refactoring

## [1.0.1] - 2021-01-10

### Changed
Expand All @@ -23,4 +36,5 @@
- Main file renamed to `bot.py`

[1.0.0]: https://github.com/finlaysawyer/discord-uptime/compare/v0.0.1...v1.0.0
[1.0.1]: https://github.com/finlaysawyer/discord-uptime/compare/v1.0.0...v1.0.1
[1.0.1]: https://github.com/finlaysawyer/discord-uptime/compare/v1.0.0...v1.0.1
[1.1.0]: https://github.com/finlaysawyer/discord-uptime/compare/v1.0.1...v1.1.0
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# discord-uptime
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)

Discord Uptime is a Discord bot that allows you to monitor the uptime of services using ICMP ping and http requests.
There are also commands avaliable to make manual requests. Built using discord.py 1.6.x, ping3 and aiohttp
Expand All @@ -14,6 +15,9 @@ Install dependencies:
Bot setup (Rename config.example.json and edit the default values):
* `token` - Discord bot token
* `prefix` - Discord bot prefix
* `activity_type` - Activity type for bot status (must be one of `playing, streaming, listening, watching`)
* `activity_name` - Text for bot status
* `disable_help` - If 'true', the default help command will be disabled
* `notification_channel` - Channel ID where down/up notifications will be sent
* `role_to_mention` - Role ID which will be tagged in down/up notifications
* `secs_between_ping` - How many seconds between each uptime check
Expand Down
19 changes: 13 additions & 6 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
import os
import sys

from discord import Intents
import discord
from discord.ext import commands
from discord.ext.commands import DefaultHelpCommand

from utils.config import get_config

Expand All @@ -21,22 +22,28 @@ def __init__(self):
command_prefix=get_config("prefix"),
description="Bot to monitor uptime of services",
reconnect=True,
intents=Intents.default(),
intents=discord.Intents.default(),
activity=discord.Activity(
type=getattr(discord.ActivityType, get_config("activity_type").lower()),
name="services",
),
help_command=DefaultHelpCommand()
if not get_config("disable_help") == "true"
else None,
)
self.bot = bot

async def on_ready(self):
print(f"Logged in as {self.user}")
logging.info("Logged in as %s", self.user)

for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
if filename.endswith(".py") and not filename.startswith("__"):
self.load_extension(f"cogs.{filename[:-3]}")

async def on_command_error(self, ctx, error):
if isinstance(error, (commands.BadArgument, commands.MissingRequiredArgument)):
return await ctx.send(error)
else:
return
return


if __name__ == "__main__":
Expand Down
Empty file added cogs/__init__.py
Empty file.
2 changes: 1 addition & 1 deletion cogs/ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async def ping(self, ctx, address: str, pings: int = 1) -> None:
elif ping(address) is None:
await ctx.send(f"Could not ping {address} - timed out.")
else:
for i in range(pings):
for _ in range(pings):
await ctx.send(
f"Received response from {address} in: "
f"{str(int(ping(address, unit='ms')))}ms."
Expand Down
3 changes: 3 additions & 0 deletions config.example.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
{
"token": "",
"prefix": ">",
"activity_type": "watching",
"activity_name": "services",
"disable_help": "false",
"notification_channel": 1234,
"role_to_mention": 1234,
"secs_between_ping": 30,
Expand Down
14 changes: 13 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,16 @@ exclude = '''
)/
| foo.py
)
'''
'''

[tool.pylint]
[tool.pylint.master]
max-line-length = 88
disable = '''
missing-module-docstring,
missing-class-docstring,
missing-function-docstring,
arguments-differ,
no-member,
duplicate-code,
'''
4 changes: 2 additions & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
aiohttp==3.7.3
async-timeout==3.0.1
attrs==20.3.0
chardet==4.0.0
chardet==3.0.4
discord.py==1.6.0
idna==3.1
multidict==5.1.0
ping3==2.6.6
typing-extensions==3.7.4.3
yarl==1.6.3
yarl==1.6.3
3 changes: 0 additions & 3 deletions setup.cfg

This file was deleted.

Empty file added utils/__init__.py
Empty file.
26 changes: 22 additions & 4 deletions utils/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,29 @@

def get_servers() -> Iterable:
"""Reads all specified servers specified in servers.json."""
with open("servers.json") as f:
return json.load(f)
with open("servers.json") as file:
try:
return json.load(file)
except json.decoder.JSONDecodeError as err:
raise Exception(
f"Couldn't load servers.json: it is formatted incorrectly "
f"on line {err.lineno} column {err.colno}"
) from err


def get_config(item: str) -> Union[str, int]:
"""Retrieves the configuration value specified."""
with open("config.json") as f:
return json.load(f)[item]
with open("config.json") as file:
try:
file = json.load(file)
except json.decoder.JSONDecodeError as err:
raise Exception(
f"Couldn't load config.json: it is formatted incorrectly "
f"on line {err.lineno} column {err.colno}"
) from err

value = file.get(item)

if value is None:
raise Exception(f"Your config is out of date! Missing a value for {item}")
return value

0 comments on commit 4661687

Please sign in to comment.