Coder Social home page Coder Social logo

python-discord / bot Goto Github PK

View Code? Open in Web Editor NEW
1.3K 72.0 637.0 16.86 MB

The community bot for the Python Discord community

Home Page: https://pythondiscord.com

License: MIT License

Python 99.97% Dockerfile 0.03%
discord-bot discord bot python python3 python312

bot's Introduction

Python Utility Bot

Discord CI License

This project is a Discord bot specifically for use with the Python Discord server. It provides numerous utilities and other tools to help keep the server running like a well-oiled machine.

Read the Contributing Guide on our website if you're interested in helping out.

bot's People

Contributors

akarys42 avatar chrislovering avatar den4200 avatar dependabot[bot] avatar gdude2002 avatar hassanabouelela avatar ikuyarihs avatar ionite34 avatar jb3 avatar jchristgit avatar kosayoda avatar ks129 avatar kwzrd avatar lemonsaurus avatar markkoz avatar mbaruh avatar mrhemlock avatar numerlor avatar rohanjnr avatar sco1 avatar scragly avatar sebastiaanz avatar senjan21 avatar shivansh-007 avatar shtlrs avatar swfarnsworth avatar tizzysaurus avatar toxickidz avatar wookie184 avatar xithrius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bot's Issues

Reddit post relays can unexpectedly freeze

Originally posted by Kingsley McDonald:

the automagic #reddit post relays appear to have frozen entirely, and reloading the cog doesn't seem to be a temporary solution to that. this has happened only once thus far, and the only notable thing that stands out as being potentially related is the fact that the relays stopped working after the top weekly posts had been sent and pinned. it isn't the first time the bot has sent and pinned weekly posts, but it certainly is the first time any problems have been observed with the relays. no related errors were found in the logs.

Django API: HTTP error handling

Originally posted by Johannes Christ:

In order to generalize our current error handling, the new API client raises HTTP errors straight to the commands. For simple cases that don't require specialized handling, we should use the command error handler in bot/cogs/events.py in order to provide a useful response.

I took an initial stab at it in https://gitlab.com/python-discord/projects/bot/merge_requests/67, which you can look at for reference, but I did not yet fully figure it out.

You will either have to fire requests against my API instance or set up your own instance of the website: see the setup documentation on the Django branch for details.

For documentation on the command handler, see https://discordpy.readthedocs.io/en/rewrite/ext/commands/api.html#discord.on_command_error.

If you have any questions, please ask.

Please leave a comment if you start to work on this issue.

Part of #67.

Even more infraction search improvements

Originally posted by Leon Sandøy:

There are still improvements that need to be made in infraction search. I'll leave this issue a bit open ended as to what the best way to implement these things is, but here's what I'd like to be able to do:

  • All searches should be case insensitive
  • Search for user by username
  • Search for user by ID
  • Search for infraction by reason
  • Search for agent by username
  • Search for agent by ID
  • Search for infractions by timespan. How many infractions did we give between last friday and wednesday?

Adding unittests

I believe the last opinion on this was faking contexts and messages in order to test every function/cog for itself. Something new on this?

Review uses of `on_ready` in cogs

Originally posted by Scragly:

There are 12 cogs that use the event on_ready to perform some form of preparation for that cog.

While that's fine if the extension is loaded before the bot is started, any cases where loading occurs after this stage will result in the preparatory tasks not being done at all, resulting in missing data the cogs rely on to function. This includes cases where a cog may be reloaded during runtime, which often happens during development to refresh to code.

Instead of running when the bot dispatches the ready event, it would be best to instead have it prepare every time a cog is loaded, but have it wait for the bot's ready flag:

class Cog:
    def __init__(self, bot):
        self.bot = bot
        ...
        bot.loop.create_task(self.prepare_method())

    async def prepare_method(self):
        await self.bot.wait_until_ready()
        # do prep stuff
        ...

This is a job for after the Github migration.

#recruitment channel system

Originally posted by Leon Sandøy:

We want to create a new channel, #recruitment, where people will be able to do recruitment. For this, we want the following system:

  1. Get an admin or owner to help you do the following:
  • Create the #recruitment channel
  • Create the #staff-approval channel
  • Come up with a input format that the user will use when posting to the #recruitment channel.
  • Come up with an output embed that the bot will use when posting in the #recruitment channel
  • Post the pin in #recruitment
  • Make the channel public once everything is live.
  1. When a user posts a message in this channel, the bot validates it.
  • If the message follows the pinned format, copy the message, delete it from the channel, and DM the user to tell them that the message has been submitted for approval and he'll be let know when we've processed it.
  • If the message doesn't follow the pinned format, copy the message, delete it from the channel, and DM the user to tell them that the message has not been submitted because it does not follow the format. Provide the user an example of the correct format, and paste in the message the user posted (so they don't lose all that stuff they typed up).
  • If the user has DM's disabled and the bot tries to DM but fails, post a temporary message in the channel instead, with a ping. 30 seconds should be enough.
  1. After the message is validated, post it in #staff-approvals
  • The message is posted in #staff-approvals in an embed, and reactions for approve and deny are added to the post.
  • The bot listens to raw_reaction events in this channel and responds accordingly
  • Only moderators or higher can make approval decisions.
  • If approval is denied, remove reactions, edit the embed so it says DENIED, and send the user a DM saying the request was denied.
  • If approval is given, post an embed in #recruitment with the information the user provided, and DM the user to let them know their request was approved.
  1. Backup systems
  • Add an !approve command that takes a message_id just in case the reactions fuck up.
  • Add a !deny command that takes a message_id just in case the reactions fuck up.

apostrophes in otnames

Originally posted by Leon Sandøy:

The is allowed in channel names. We should insert it into all existing channel names that have contractions (dont-do-this, dont-do-that), and change the otnames add feature so that it accepts , and also so that it converts ' into so we don't have to type some weird unicode character every time we make a name.

Support for new Django API

Originally posted by Johannes Christ:

We need to generalize the current way of working with the site. Simply speaking, the Django rewrite of the site has abstracted away most of the API endpoint setup and they are more or less the same with some minor differences.
Therefore, I propose we use a single API client class instead of writing extra methods in order to fetch tags, watched users etc. in each of the cogs. Some initial work was done here: https://gitlab.com/python-discord/projects/bot/merge_requests/67

Since the Django site rewrite is not live, all branches related to this issue must be based off the Django branch, and the merge requests must be opened with the django branch as the source branch.

For testing locally, you can either set the site up yourself (which I'd recommend, since you get to see what's going on) or ask me for a token on my "staging" instance of the website.

Please refer to the linked merge request for how to use the new API calls in your code.

Infractions improvements

Originally posted by Gareth Coles:

  • Warns should be logged to the mod-log
  • There should be a note infraction thst doesn't count towards a user's infraction count (and maybe isn't shown in the search in public channels?)
  • We should be able to submit images for infractions, including by attaching them directly to the command message when creating one

Cog load with duplicate command reporting wrong error

Originally posted by Scragly:

In the cogs extension module, there's a try: except ClientException. The reason for the error is hardcoded, assuming that it raises only when a setup function does not exist.

Click here to view the relevant code.

Unfortunately, the same exception will also raise down the stack in bot.add_cog when a command within the cog has a name that's already existing in commands, conflicting and raising the exception.

To avoid incorrect errors being reported/logged, and to prevent confusion during debugging, it might be best to simply remove the except ClientException block and let it fall down into the catchall except Exception as e block which prints the exception details as given.

Feel free to comment better suggestions, of course.

This will be something for after the migration over to GitHub, hence why it's an Issue, rather than a quick MR.

Snakify error

"Command raised an exception: RecursionError: maximum recursion depth exceeded while calling a Python object"
aasdf

Use wait_for_deletion for codeblocks

Originally posted by Leon Sandøy:

In #73, we created a util to handle waiting for reaction and then deleting a message in bot.utils.messages. This should be used for codeblock messages as well.

Moderation commands don't compare role hierachy of caller and "moderated"

Originally posted by Thomas Petersson:

Since the bot straight out bans, kicks, etc. after posting an infraction, won't it be possible for moderators to ban admins. Given the bots role is above admins. This makes it more of a trust based implementation over restricted.

In my opinion admins should not be able to moderate other admins, and moderators should definitely not be able to moderate admins (owners are above the bot in the hierarchy and can't be effected)

attempted murder

If it was not for the fact that joseph is an owner (and super duper owner) and the bot is under owner role in the hierarchy that may have very well gone through. (We were curious, didn't intend to try to ban Joseph)

Django API Support: Prettier HTTP error responses

Originally posted by Johannes Christ:

The current responses returned when something goes wrong from the Django API are very crude. We should display embeds and random error messages instead. The relevant code can be found here: https://gitlab.com/python-discord/projects/bot/blob/django/bot/cogs/events.py#L138-143

To set up the bot to work with the new site, you can either ask me for an API key on my instance or set up your own. See the Django branch on the site project for more information.

This is labelled as a good first issue - if you have any questions about this, don't hesitate to ask!

Possibly track when a user was last online/active

Originally posted by ByteCommander:

It could be useful to know when an account has last been active in the server (e.g. events like sending messages, reactions, deleting messages, maybe changing nick) or even been visibly online in general. This could be integrated into the general user info command, or queried with a new bot command.

To avoid stalking/abuse potential, the reported time should probably be rounded to at least whole days, or for longer time spans even weeks for posting in public channels.

The data would have to be gathered by logging the time stamps (again, rounding this to e.g. full hours or maybe even full UTC days could be desirable) of user actions and status/visibility changes. Only the last value for both activity and visibility should be saved each, no history.

Additional things to do with this data include showing accumulated stats about how many people have been inactive/invisible for how long periods of time. Possibly it could even be used to notify and in a second step prune members that were inactive and never online for extended periods, like 6 months or a year (dead accounts).

"help" menu for aliases

Originally posted by Thomas Petersson:

Would probably be helpful to see which are available and change them without having to change sourcecode.
(will look into soon tm)

Superstarify data cleanup and expansion.

Originally posted by Leon Sandøy:

The superstarify only has 75-ish artists, and some of them are still groups. Please change the data to be as follows:

  • All artists on the list should be individuals.
  • There should be artists from many genres. Hiphop, metal, classical, jazz, represent most major genres.
  • There should be at least a few hundred different artists on the list, as many as possible.

Reminder: Build "Remind" feature for bot.

As a user I want to be able to set reminders for posts I made or others made.
The reminder should include a due-time (hours/days/specific date) and be able to link to the post in question.

Wolfram custom cooldowns being triggered on help output

Originally posted by Scragly:

The custom cooldowns in the wolfram cogs have been implemented as a command check instead of a command cooldown. Due to this, anytime command.can_run is called the cooldowns end up triggering it's usage, even if it wasn't from a command invocation, but just a check for displaying in the help command or similar situations.

This will need to be changed to a proper cooldown implementation to avoid having any non-invoke check count towards the usage limit unnecessarily.

Change bb watch to accept a note input

Originally posted by sco1:

With the impending merge of the notes cog, it would be nice if !bb watch took advantage of the cog and allowed us to store a note when someone is watched so others can track it in the future.

Right now it seems like the optional "log to channel" input is being used, so it seems like it makes sense to replace this input with a notes entry, similar to how warn/kick/ban/etc. are set up.

Consistent Error Responses

Some errors use plain messages (e.g. general error handlers and moderation cogs) while others use embeds, sometimes even including humorous replies (e.g. reminders and clean cogs). Errors don't necessarily refer to CommandError here - it could be any error that is being handled, even ones that aren't exceptions.

Embeds have more formatting options, allow room for those humorous replies, and are more prominent in the sense that 1. bigger = more noticeable and 2. can't be confused for a regular user's message. On the other hand, plain messages have less clutter around them and are simpler to create in code (may be a moot point if a generic utility function is added to create the embeds).

  • Should the plain/embed be mutually exclusive? In other words, should everything only use one of them to stay consistent, or should some things be allowed use the other? If not, which should be used by what?
  • What style(s) should be used to stay consistent? Should the humorous replies always be used? Should plain messages always be prefixed by emojis?
  • Can and should a generic function be written to create these error messages? #674 is doing that for embeds.

All the areas where errors are being handled should be identified so that it is clear what changes need to be made and where.

Originally posted by Kingsley McDonald:

many error responses in the Moderation cog aren't sent as an embed. instead, the messages are sent with a very simple (and ugly) ❌. all occurrences of this should be changed to be consistent with the rest of the bot's responses.

Humanizing a time can return an empty string.

Originally posted by Kingsley McDonald:

the bot.utils.time.humanize function strips the resulting time of trailing 0 times. for example, "0 days 5 hours" would become "5 hours". this means that when the result is something like "0 days", it just returns an empty string. perhaps it should return the "0 days" as it is, to avoid situations like this:

image

(thanks for the screenshot, gdude. :D)

Superstarify modlog embed

Originally posted by Leon Sandøy:

Currently Superstarify events have a terrible 🖕 thing in the modlog. They should obviously have a nice embed instead like other moderator actions do.

Disable all bot commands but !accept in checkpoint

Originally posted by ByteCommander:

The #checkpoint channel is where new members have to go to type !accept in order to verify they have read the rules and to get access to all other public channels.

Currently, the bot removes all user messages from #checkpoint immediately, to keep it clean. If the user types anything other than !accept, they additionally get a warning which self-destructs after short time.

However, other bot commands are still working, and while the user's original command message will be removed, any command responses will still get posted and do not seem to ever get deleted automatically.

image

This seems to be a bug that allows people spamming the checkpoint channel to annoy yet to be verified users.

As a solution, all commands except for !accept should be entirely disabled in #checkpoint.

Add `pydoc` command

The standard library has a module pydoc which can be used for generating and viewing documentation. I suggest a command such as [prefix] pydoc <NAME> which calls pydoc.doc with the given name to show instant documentation. I feel like this could be useful when referring to a certain method when helping someone - here's an example with str.find:

>>> import io
>>> import pydoc
>>> out = io.StringIO()
>>> pydoc.doc('str.find', output=out)
>>> print(out.getvalue())
Python Library Documentation: method_descriptor in str

str.find = find(...)
    S.find(sub[, start[, end]]) -> int
    
    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.
    
    Return -1 on failure.

for "bigger" documentation such as help(dict), this generates quite the long output. It might be a good idea to truncate this or put it into a "pageable embed" (with reactions to move around). Also, I've yet to figure out if it's somehow possible to include a link to the official docs..

Command errors outside of guilds

Originally posted by Johannes Christ:

Some commands currently expect a guild to be there, therefore message.guild is None:

image

An easy solution would be applying the @commands.guild_only decorator on commands using guilds explicitly.

Update Pipfile.lock

Originally posted by Mark:

There are several issues with our dependencies:

  1. discord.py should be added as a git URL rather than using the zip URL. This will allow it have a ref and thus be locked to a specific version of the library.
  2. The locked aiohttp (==2.2.5) and websockets (==4.0.1) versions do not satisfy the current requirements of discord.py.
  3. flake8 should be updated to 3.6.0 as it currently misses some errors that we would presumably want to catch (well, maybe W605 is a false positive). See this for all errors in the project which it is currently missing.

Settle on one style for quotes for strings

This issue is intended as a primary discussion thread for the debate raised in #53, in which several ideas about quotation were raised, including:

  • Using " primarily, and ' when double quotes are in the string.
  • Using ' for short words and " for sentences

This issue will be closed as soon as we have found something to use consistently in the project, and a PR has been made to close this issue by fixing all existing strings.

Aliases to add

Originally posted by Thomas Petersson:

More of a personal memo, but add aliases for

  • !tags get f-strings
  • !tags get codeblock

Any other additions are welcome.

Better Discord error handling

Originally posted by Leon Sandøy:

Currently, innocent Discord errors such as "this command does not exist" or "could not find that user" are not being handled by the command error handler. As a result, the bot logs a lot of stacktraces for relatively innocent things.

See the following paste for examples: https://paste.pythondiscord.com/uwopupoyun.py

Investigate the problem, create logic to handle these types of errors, and merge request it to the bot.

Top 5 leaderboard for mod-alert triggers.

Originally posted by Leon Sandøy:

Let's make a simple leaderboard for mod-alert triggerers. It should only be usable in staff channels like #admins and #staff, and only by mods or higher. We'll track mod-alert triggers in the database, so it'll need a site MR as well.

Replace RMQ with Tasks

Originally posted by Leon Sandøy:

We should remove the RMQ integration, and replace it instead with Tasks, as described in https://gitlab.com/python-discord/projects/site/issues/45. The RMQ code is an unholy mess that nobody likes working with, and a simple one-way-communication system is far simpler for contribs and core devs alike to wrap their heads around. It also wouldn't really perform very differently anyway, so for our use case it should be perfect.

The Task interface should be abstracted away so that our contribs never have to worry about doing the actual polling. The bot should just do this and then trigger a sort of task event, that our contribs can write handlers for. This should be as simple as possible, and it would be ideal if it mimics how events work in discord.py already. perhaps an on_task_received event handler that can optionally be defined for each cog, and some sort of constant to define relationships between task types and cog? Something like that.

Evals custom check uses top_role for whitelists, event handlers can't use it in help channels.

Originally posted by Thomas Petersson:


async def channel_is_whitelisted_or_author_can_bypass(ctx: Context):
    """
    Checks that the author is either helper or above
    or the channel is a whitelisted channel.
    """

    if ctx.channel.id not in WHITELISTED_CHANNELS and ctx.author.top_role.id not in BYPASS_ROLES:
        raise MissingPermissions("You are not allowed to do that here.")

    return True

This custom check in snekbox.py is checking toproles for whitelists, which means a helper with the event handler role for instance wont be able to use eval because their top role is not whitelisted.

Don't allow doubled actions. E.g. you shouldn't be able to mute muted users.

Originally posted by Leon Sandøy:

You shouldn't be able to unwatch an unwatched user, or mute a muted user. The bot should simply say "oops, that user is already muted / banned / is not on the server (if you try to kick) / isn't currently being watched / ..."

Go through the bot, find cases like these, and fix'em.

Soft decoupling of site and bot

Originally posted by Leon Sandøy:

  • write a wrapper for the api code in the bot so that web calling code doesn't have to live in the cogs.
  • decouple all the services from the bot for local dev, so that you can run it without the site or rabbitmq without incurring more than a simple warning that tells them exactly what that entails and how to fix it.
  • do the same for the site. site should work sans rabbitmq
  • make django fall back to sqlite in order to remove database from local dev requirements completely.
  • no more docker-compose, because now you only need rabbitmq, and only if you're writing any service-interoperable stuff. which is rare.

Add a way to close bot messages

If a user enters code without formatting, the bot will reply with the message on how to format python code in discord.
I feel like it would be nice if there's a way to close this message either by helpers/admins/moderators or by the person who typed the wrongly formatted message him/herself by reacting with some emoji (like how you can do paging)

It would keep the discord chat flowing nicely instead of scrolling back over bot interruptions.

We would then also need to find a way to keep the mod-log clean though.

Delete eval Results

Originally posted by Mark:

Add a way to delete eval results similar to how it was done for the code block tag. Sometimes I make a mistake and have no choice but to live with it cluttering up the chat. Sound easy enough; I'll gladly submit an MR for this myself.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.