Git Product home page Git Product logo

kkrypt0nn / python-discord-bot-template Goto Github PK

View Code? Open in Web Editor NEW
820.0 21.0 291.0 155 KB

🐍 A simple template to start to code your own and personalized Discord bot in the Python programming language

Home Page: https://krypton.ninja

License: Apache License 2.0

Python 100.00%
discord-bot python krypton user-discord python-bot python-discord-bot python-discord-bot-template discord-bot-template discord-server discord-py

python-discord-bot-template's Introduction

Python Discord Bot Template

This repository is a template that everyone can use for the start of their discord bot.

When I first started creating my discord bot it took me a while to get everything setup and working with cogs and more. I would've been happy if there were any template existing. However, there wasn't any existing template. That's why I decided to create my own template to let you guys create your discord bot easily.

Please note that this template is not supposed to be the best template, but a good template to start learning how discord.py works and to make your own bot easily.

If you plan to use this template to make your own template or bot, you have to:

  • Keep the credits, and a link to this repository in all the files that contains my code
  • Keep the same license for unchanged code

See the license file for more information, I reserve the right to take down any repository that does not meet these requirements.

Support

Before requesting support, you should know that this template requires you to have at least a basic knowledge of Python and the library is made for advanced users. Do not use this template if you don't know the basics or some advanced topics such as OOP or async. Here's a link for resources to learn python.

If you need some help for something, do not hesitate to join my discord server here.

All the updates of the template are available here.

Disclaimer

Slash commands can take some time to get registered globally, so if you want to test a command you should use the @app_commands.guilds() decorator so that it gets registered instantly. Example:

@commands.hybrid_command(
  name="command",
  description="Command description",
)
@app_commands.guilds(discord.Object(id=GUILD_ID)) # Place your guild ID here

When using the template you confirm that you have read the license and comprehend that I can take down your repository if you do not meet these requirements.

How to download it

This repository is now a template, on the top left you can simply click on "Use this template" to create a GitHub repository based on this template.

Alternatively you can do the following:

How to set up

To set up the bot it was made as simple as possible.

config.json file

There is config.json file where you can put the needed things to edit.

Here is an explanation of what everything is:

Variable What it is
YOUR_BOT_PREFIX_HERE The prefix you want to use for normal commands
YOUR_BOT_INVITE_LINK_HERE The link to invite the bot

.env file

To set up the token you will have to either make use of the .env.example file, either copy or rename it to .env and replace YOUR_BOT_TOKEN_HERE with your bot's token.

Alternatively you can simply create an environment variable named TOKEN.

How to start

To start the bot you simply need to launch, either your terminal (Linux, Mac & Windows), or your Command Prompt ( Windows) .

Before running the bot you will need to install all the requirements with this command:

python -m pip install -r requirements.txt

After that you can start it with

python bot.py

Note You may need to replace python with py, python3, python3.11, etc. depending on what Python versions you have installed on the machine.

Issues or Questions

If you have any issues or questions of how to code a specific command, you can:

  • Join my discord server here
  • Post them here

Me or other people will take their time to answer and help you.

Versioning

We use SemVer for versioning. For the versions available, see the tags on this repository.

Built With

License

This project is licensed under the Apache License 2.0 - see the LICENSE.md file for details

python-discord-bot-template's People

Contributors

e0lnt3xbmlcy45pnscomb2qr1zl5ftckljzmgu2 avatar kkrypt0nn avatar shndowbots avatar sound-infinity 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

python-discord-bot-template's Issues

Logging warns

so i mean if l warned a user 2 times it says in the bottem of the embed this is the (Users name) 1st warn

Not working

I edited everything in the script and went to command prompt put in the command and I hit enter and nothing happend, what do I do?
Annotation 2020-09-09 190711

Can't use the help commands

I can't use the help command, i just trying to make my own command and adding a new class inside "cpanel.py" file. Anyway, the command still work. But when i trying to see the command in help. It seems to never work. Is this a bug or what?

`import json
import os
import sys
import discord

from discord.ext import commands

if not os.path.isfile("config.json"):
sys.exit("'config.json' not found! Please add it and try again.")
else:
with open("config.json") as file:
config = json.load(file)

class cPanel(commands.Cog, name="cPanel"):
def init(self, bot):
self.bot = bot

@commands.command(name="test")
async def test(self, context):
    """
    Testing some new commands to check if it works
    """
    await context.send("Ok, it's working man")

And then we finally add the cog to the bot so that it can load, unload, reload and use it's content.

def setup(bot):
bot.add_cog(cPanel(bot))`

I'm dizzy because of this and i 'll left this python alone. I 'll try the node.js one

Can't install disnake

I have been trying to do pip install disnake but it only shows this:
C:\Users\blued\Documents\GitHub\DiscordBotTest>pip install disnake
WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip.
Please see pypa/pip#5599 for advice on fixing the underlying issue.
To avoid this problem you can invoke Python with '-m pip' instead of running pip directly.
ERROR: Could not find a version that satisfies the requirement disnake (from versions: none)
ERROR: No matching distribution found for disnake

If anyone knows what is happening please help me

Improper token has been passed

┌──(senpai㉿senpai)-[~/tools/Python-Discord-Bot-Template]
└─$ python bot.py
Loaded extension 'fun-slash'
Loaded extension 'owner-slash'
Loaded extension 'moderation-slash'
Loaded extension 'template-slash'
Loaded extension 'general-slash'
Loaded extension 'fun-normal'
Loaded extension 'moderation-normal'
Loaded extension 'general-normal'
Loaded extension 'template-normal'
Loaded extension 'owner-normal'
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/dist-packages/disnake/http.py", line 467, in static_login
    data: user.User = await self.request(Route("GET", "/users/@me"))
  File "/usr/local/lib/python3.9/dist-packages/disnake/http.py", line 420, in request
    raise HTTPException(response, data)
disnake.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/senpai/tools/Python-Discord-Bot-Template/bot.py", line 216, in <module>
    bot.run(config["token"])
  File "/usr/local/lib/python3.9/dist-packages/disnake/client.py", line 856, in run
    return future.result()
  File "/usr/local/lib/python3.9/dist-packages/disnake/client.py", line 835, in runner
    await self.start(*args, **kwargs)
  File "/usr/local/lib/python3.9/dist-packages/disnake/client.py", line 798, in start
    await self.login(token)
  File "/usr/local/lib/python3.9/dist-packages/disnake/client.py", line 658, in login
    data = await self.http.static_login(token.strip())
  File "/usr/local/lib/python3.9/dist-packages/disnake/http.py", line 471, in static_login
    raise LoginFailure("Improper token has been passed.") from exc
disnake.errors.LoginFailure: Improper token has been passed.

Improper token has been passed error

hello dear developer :)

Here I have a problem and this problem comes back on all the bots that I have and even with yours that I have just tested.

The bot tells me that my Token and "Improper token has been passed"

except it's the right one :) I even tried to reset it to put the new one and still the same message...

I specify that above all the bots on discord developer worked very well and for some time nothing has worked and I can't use any bot :(

do you know where the problem comes from? don't tell me it's from my Token before I had discord bots and it works great.

Thanks in advance, the error code and below:

PS C:\Users\tremp\Desktop\Python-Discord-Bot-Template-main> python bot.py
2023-03-15 20:08:55 INFO     discord_bot Loaded extension 'fun'
2023-03-15 20:08:55 INFO     discord_bot Loaded extension 'general'
2023-03-15 20:08:55 INFO     discord_bot Loaded extension 'moderation'
2023-03-15 20:08:55 INFO     discord_bot Loaded extension 'owner'
2023-03-15 20:08:55 INFO     discord_bot Loaded extension 'template'
2023-03-15 20:08:55 WARNING  discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.     
2023-03-15 20:08:55 INFO     discord.client logging in using static token
Traceback (most recent call last):
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\http.py", line 801, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\http.py", line 744, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\tremp\Desktop\Python-Discord-Bot-Template-main\bot.py", line 305, in <module>
    bot.run(config["token"])
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 860, in run
    asyncio.run(runner())
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\asyncio\runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\asyncio\base_events.py", line 647, in run_until_complete
    return future.result()
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 849, in runner
    await self.start(token, reconnect=reconnect)
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 777, in start
    await self.login(token)
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 612, in login
    data = await self.http.static_login(token)
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\http.py", line 805, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0330B778>
Traceback (most recent call last):
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\asyncio\base_events.py", line 751, in call_soon
    self._check_closed()
  File "C:\Users\tremp\AppData\Local\Programs\Python\Python39-32\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

Over 50 roles displays as `>>>> Displayin [50/50] Roles` in /serverinfo

Describe the bug
For a server with more than 50 roles, /serverinfo will claim there are exactly 50 roles (and there's a typo)

To Reproduce

  1. Create 72 roles (or really 51 or more)
  2. Call /serverinfo

Expected behavior
List of roles ends with >>>> Displaying [50/72] Roles

Screenshots
I don't have a server with that many roles

Template Version
6.1.0

Additional context
Proposed fix (the index hashes are possibly wrong since it's from a template copy)

diff --git a/cogs/general.py b/cogs/general.py
index 59af594..762613b 100644
--- a/cogs/general.py
+++ b/cogs/general.py
@@ -129,9 +129,10 @@ class General(commands.Cog, name="general"):
         :param context: The hybrid command context.
         """
         roles = [role.name for role in context.guild.roles]
-        if len(roles) > 50:
+        num_roles = len(roles)
+        if num_roles > 50:
             roles = roles[:50]
-            roles.append(f">>>> Displayin [50/{len(roles)}] Roles")
+            roles.append(f">>>> Displaying [50/{num_roles}] Roles")
         roles = ", ".join(roles)
 
         embed = discord.Embed(

Create a simple wiki

It's supposed to make the README.md file a bit cleaner with less content, and link to that wiki for things like setup, FAQs, etc.

Anyone is more than welcome to work on that.

SyncWarning: Failed to overwrite global commands

Hello, first of all thanks for the template! It works and is very easy to understand. My bot is working and running and responding to my custom commands but I dont know why I get that sometimes.

python bot.py


Loaded extension 'general-slash'
/home/maparla/anaconda3/envs/cenv/lib/python3.10/site-packages/disnake/ext/commands/interaction_bot_base.py:715: SyncWarning: Failed to overwrite global commands due to 400 Bad Request (error code: 50035): Invalid Form Body
In 0.options.2.name: String value did not match validation regex.
  warnings.warn(f"Failed to overwrite global commands due to {e}", SyncWarning)
Logged in as ChickHelp
disnake API version: 2.3.0
Python version: 3.10.0
Running on: Linux 5.11.0-46-generic (posix)

Migration to discord.py 2.0

As discord.py 2.0 has been officially released on PyPi I will make the migration back to discord.py as soon as possible for the next template version.

It might take some time but I will try to do it within the coming week

Event to handle cuss words

I have a code snippet that automatically deletes messages with cuss words, tags the person and responds with the message 'Your message has not passed moderation'. Please respond if you'd like this feature to be implemented in the bot.py file in root directory.

sqlite3 downloading error

Hello There!
I am opening this issue with regards to the 'requirements.txt' file as it cannot download sqlite3 stating the following error

ERROR: Could not find a version that satisfies the requirement sqlite3 (from versions: none)
ERROR: No matching distribution found for sqlite3

Running On Latest Python & PIP Version
I am wondering if this is an error of PIP or of the requirements.txt file

No commands

I can't run any commands with the prefix and /. Then / commands doesn't even show up.

I need some help

I get "Extension 'cogs.slash.ticket-slash' raised an error: ImportError: cannot import name 'database' from 'utils'" when I run "python bot.py" I have uninstalled utils and installed it again and nothing is working

ModuleNotFoundError: No module named 'aiosqlite'

Yes, I installed it by:
python -m pip install -r requirements.txt
yet it is still not being imported, I uninstall and reinstall it, but it still didn't work.
Is this a high-skill issue?
Please help.

Bot doesn't run

Hello, I love your template and have followed all of the steps to making the bot but when I put in python3 bot.py into Command prompt it comes up with this, please help!
Annotation 2020-05-29 092050

Move database from json to sql

As the title says, move the example from json to an sql-like database, such as sqlite. This imposes the challenge of the user having to set up a database, which is good experience for the user and teaches them not to use storage types such as json.

#59

Exception when running slash commands in DM with bot

As title. This is the exception. It fires on most commands.

Ignoring exception in on_slash_command
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/disnake/client.py", line 612, in _run_event
await coro(*args, **kwargs)
File "./bot.py", line 147, in on_slash_command
f"Executed {interaction.data.name} command in {interaction.guild.name} (ID: {interaction.guild.id}) by {interaction.author} (ID: {interaction.author.id})")
AttributeError: 'NoneType' object has no attribute 'name'

This error does not appear in channels. The f-string renders properly there.
So... either interaction.guild or interaction.data is returning NoneType I guess. Idk.

Good work! This error gets ignored and the bot continues working just fine.

How to use

I try to open the bot file and it opens blank then really quickly writes like 100 lines of code then shuts down and nothing happens, So where do I actually access the code?

Cogs not loading and Help command missing

Atm you forgot to add back the help.py command so the template is unable right now. Also, every command I run comes back with this error:

Ignoring exception in on_command_error Traceback (most recent call last): File "C:\Users\peyto\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event await coro(*args, **kwargs) File "d:\Default Download\Python-Discord-Bot-Template-master\Python-Discord-Bot-Template-master\bot.py", line 117, in on_command_error raise error discord.ext.commands.errors.CommandNotFound: Command "randomfact" is not found

Bitcoin price fails with unexpected mimetype "application/json"

Describe the bug
The bitcoin command fails to parse the response since Coindesk have fixed their API.
discord.app_commands.errors.CommandInvokeError: Command 'bitcoin' raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: application/json; charset=utf-8', url=URL('https://api.coindesk.com/v1/bpi/currentprice/BTC.json')

To Reproduce
Run /bitcoin

Expected behavior
An embed with the current price of bitcoin is displayed

Template Version
6.1.0

Additional context
Coindesk seems to have fixed their API to return the correct MIME type. Previously it returned application/javascript as noted in the code. I would propose removing the explicit content_type (default application/json) or setting it to None to explicitly ignore MIME type.

load_cogs not awaited

When some cog isn't loaded, it generates an asyncio runtime error because it was not awaited.

Switch lisence

The Apache License gives you copyright ownership of the template, which means that bots made using this template are (partially) owned by you. This severely limits how we can use the template. I suggest using a copyleft license such as GPL.

JSON file error

============================Output============================
Traceback (most recent call last):
File "C:\Users\Bang1338\Desktop\a\bot.py", line 26, in
config = json.load(file)
File "C:\Users\Bang1338\AppData\Local\Programs\Python\Python38-32\lib\json_init_.py", line 293, in load
return loads(fp.read(),
File "C:\Users\Bang1338\AppData\Local\Programs\Python\Python38-32\lib\json_init_.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\Bang1338\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Bang1338\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 4 column 14 (char 131)
============================End============================
I don't know what is that but... 5 error at same time

command errors

the bot isn't responding to the commands and says they aren't to be found in the terminal, what should I do?

Lock command if you need it (I saw it in TODO.md)

I don't really know how slash commands work but here you go.

@commands.command(name="lock")
@commands.has_permissions(manage_channels=True)
async def lock(self, context, channel: discord.TextChannel=None):
    channel = channel or context.channel
    overwrite = channel.overwrites_for(context.guild.default_role)
    overwrite.send_messages = False
    overwrite.add_reactions = False
    await channel.set_permissions(context.guild.default_role, overwrite=overwrite)
    await context.send(':lock: Channel locked.')
    
@commands.command(name="unlock")
@commands.has_permissions(manage_channels=True)
async def unlock(self, context, channel: discord.TextChannel=None):
    channel = channel or context.channel
    overwrite = channel.overwrites_for(context.guild.default_role)
    overwrite.send_messages = True
    overwrite.add_reactions = True
    await channel.set_permissions(context.guild.default_role, overwrite=overwrite)
    await context.send(':closed_lock_with_key: Channel unlocked.')

slash commands

went does @cog_ext.cog_slash( name="command", description="Command description", guild_ids=[GUILD_ID1, GUILD_ID2] )
go?

intents module error

getting this error
in
intents = discord.Intents.default()
AttributeError: module 'discord' has no attribute 'Intents'

Any ideas how to fix it?

[enh] Start supporting slash command

Slash Commands are actually in open beta phase but will soon™ become stable, they're supported by discord.py as an official addon (discord-py-slash-commands).

It would be great for this template to support those commands, maybe on a separate branch because not all people wants to use them because of the beta-buggy status of those ones at the moment.

Serverinfo command not working

server info command does not work i get this error every time i run it AttributeError: 'NoneType' object has no attribute 'id'

Bot response to unknown command

is there any way where you can make it where if a command is not found then the bot sends Command (What they tried to run) not found

config error

it keeps on saying the config isn't in the folder but it is anyone have a fix?

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.