Code Monkey home page Code Monkey logo

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

View Code? Open in Web Editor NEW
819.0 819.0 286.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 discord-automation discord-bot discord-bot-template discord-net discord-py discord-server discord-slash-commands discordapp discordbot disnake krypton python python-bot python-discord-bot python-discord-bot-template slash-commands user-discord

python-discord-bot-template's Introduction

πŸ‘‹ Hey, I'm Krypton!

Note: In the army until at least the 18th of November 2024 - won't be much available until then.

Hey there, I’m Krypton! (Coming from the Krypton element 36 βš›οΈ) I’m a small developer, competitive shooter and wannabe security researcher. I like computers (surprised?) and anything related to cyber security, especially reverse engineering and networking.

I πŸ’œ open source


Discord β€’ Email β€’ Keybase β€’ Website

  • πŸ› οΈ I'm currently working on too many side projects.
  • 🌱 I'm currently learning Rust & Reverse Engineering.
  • πŸ’­ Ask me things about anything and I will try to answer.
  • πŸ“‡ Contact me: @krypton.ninja on Discord, @kkrypt0nn on Twitter, per Email or kkrypt0nn on Keybase.
  • πŸΊπŸ’œπŸ’š Fun facts: My favorite animal is a wolf and one of my favorite colors are #BEBEFE, or any type of purple, and any type of green.

πŸ“© Latest blog posts


πŸ’° Donate Me
  • GitHub Sponsors: Click here
  • Buy Me a Coffee: Click here
  • Ko-fi: Click here
  • Bitcoin: 31mGvXAhWJbhSwdgx9F2mVPguPRFCYYFwL
  • Ethereum: 0x20257228C9e94A13E4BB9578635c84403cAb6E60
  • Dogecoin: D9hhH53pSe2KXPBvVQLe5G5FTvrmWnjtW4
  • Dash: XiJKVXoeR6nMCnhYQSM3DEHtMdubUjtLeC
  • PayPal: Click here

If you donate with crypto currency, make sure you send the coins to the address corresponding to the currency. Sending to any other address will cause a loss of the coins and it will be impossible to recover, I am not responsible for an issue like that.


⏳ Time Spent
No activity tracked

πŸ“ˆ GitHub Statistics

GitHub Statistics

Profile Views

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

python-discord-bot-template's Issues

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.')

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'
ξΊ§

intents module error

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

Any ideas how to fix it?

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(

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

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.

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

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

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.

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.

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

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.

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

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)

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.

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

slash commands

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

load_cogs not awaited

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

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

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

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?

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

config error

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

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

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.

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

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?

No commands

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

[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.

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

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

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.

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.