#discord-bots
1 messages ยท Page 343 of 1
This is the code I use rn but it doesnt make it an animated emoji
Does work on statics tho
<a:emoji_name:emoji_id>
๐ญ
@discord.ui.button(emoji=right_arrow, style=discord.ButtonStyle.blurple)
async def next(self, interaction: discord.Interaction, button: discord.Button):
self.index += 1
await self.edit_page(interaction)โ
i have this button which is working but buttons are buffering and showing interaction failed Image 1
Image 2
how was edit_page implemented?
interaction failed means you didnt respond to the interaction
I have a /say command for the bot and im wanting you to be able to edit a message that has been sent by the bot how can I do this? Also is it possible to put that message into your typing bar so you don't have to retype the whole message?
how to i make a subgroup in app_commands.Group
!d discord.app_commands.Group - pass the group that you want to be the parent of a new group in the parent argument
class discord.app_commands.Group(*, name=..., description=..., parent=None, guild_ids=None, guild_only=..., nsfw=..., auto_locale_strings=True, default_permissions=..., extras=...)```
A class that implements an application command group.
These are usually inherited rather than created manually.
Decorators such as [`guild_only()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guild_only), [`guilds()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.guilds), and [`default_permissions()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.default_permissions) will apply to the group if used on top of a subclass. For example:
```py
from discord import app_commands
@app_commands.guild_only()
class MyGroup(app_commands.Group):
pass
```...
so i do
class pokemon(Group):
-----
class info(pokemon):
```??
i did something like this
info = Group(name="info", description="Get information about a pokemon")
play = Group(name="play", description="Play pokemon games")
class Pokemon(Cog):
def __init__(self, bot):
self.bot = bot
pokemon = Group(name="pokemon", description="Pokemon commands", guild_only=True)
pokemon.add_command(info)
but i still have all the info and play commands in the Cog
task = app_commands.Group(name="task", description="Task")
@task.command(name="set", description="Set task.")
@fiery girder Here's an example
It needs experience. Why not hire someone?
def __init__(self, bot):
self.bot = bot
pokemon = app_commands.Group(name="pokemon", description="Pokemon commands", guild_only=True)
@pokemon.command(name="info", description="Info")```
@fiery girder
Message me I'll help
Yes
thats to make a command no a subgroup
discord bot is simple
i mean i have over 9k lines of discord code on this single project
what you wannna learn
you want to make a simple moderation bot or game or etc you just need to be cretiive and know how to use the stuff you learn to make endless things
what boot
is this still alive as it used to be
good question
That's a sub command bro
def __init__(self, bot):
self.bot = bot
pokemon = app_commands.Group(name="pokemon", description="Pokemon commands", guild_only=True)
@pokemon.command(name="info", description="Info")
async def info(self, interaction: Interaction):
...```
/pokemon info would be a command this way
How weird is it to do something like this?
https://github.com/Cypheriel/gary/blob/main/gary/__main__.py#L18-L22
gary/__main__.py lines 18 to 22
COGS: list[str] = [
dir.name[:-3]
for dir in (resources.files(__package__) / "cogs").iterdir()
if not dir.name.startswith("_") and dir.name.endswith(".py")
]```
COGS, of course, is used here: https://github.com/Cypheriel/gary/blob/main/gary/__main__.py#L47-L52
gary/__main__.py lines 47 to 52
if __name__ == "__main__":
for cog in COGS:
logger.info(f"[cyan]Loading the [bright_cyan]{cog.replace('_', ' ').title()}[/] cog...[/]")
bot.load_extension(f"gary.cogs.{cog}")
bot.run(getenv("TOKEN"))```
that's fine, as long as you dont reinvent the wheel, you could also just use glob.glob for the same logic
I wasn't sure how that works with importlib.resources.files
im trying to add buttons to switch between embeds but i always get this error if i press a button:
Ignoring exception in view <IncidentView timeout=180.0 children=2> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='โถ๏ธ' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\ui\view.py", line 375, in _scheduled_task
await item.callback(interaction)
TypeError: next_page() takes 2 positional arguments but 3 were given
This is the whole code https://pastebin.com/SZ6HVspq
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
dynamically loading cogs? that's fine IMO
i do something similar
bot/utils/exts.py lines 44 to 55
for module_info in pkgutil.walk_packages(module.__path__, f"{module.__name__}.", onerror=on_error):
if ignore_module(module_info):
# Ignore modules/packages that have a name starting with an underscore anywhere in their trees.
continue
if module_info.ispkg:
imported = importlib.import_module(module_info.name)
if not inspect.isfunction(getattr(imported, "setup", None)):
# If it lacks a setup function, it's not an extension.
continue
modules.add(module_info.name)```
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
hey people, I'm trying to make a music command for my bot, but when it is run, it keeps saying "Can't find file specified" I don't know why
Please provide code with more details
i want ask question,i want install discord.py and use app_command, but it always said
ERROR: Could not find a version that satisfies the requirement discord.py==2.3.2 (from versions: 0.1.0, 0.2.0, 0.2.1, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.7.0, 0.8.0, 0.9.0, 0.9.1, 0.9.2, 0.10.0, 0.11.0, 0.12.0, 0.13.0, 0.14.0, 0.14.1, 0.
14.2, 0.14.3, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.16.7, 0.16.8, 0.16.9, 0.16.10, 0.16.11, 0.16.12, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3)
what should i do then i can use app_command
what python version are you on?
its 3.8+
it showing only up to discord.py==1.7.3 implies your python version is lower than 3.8
that's... interesting, but it does show is 3.11.2
what command did you write to install discord.py
cmd
well? is it pip?
yes use
pip install discord.py
type pip --version
it pip (python 3.11)
can you show me the whole thing instead of suppressing a lot of info, like i can't tell if you're in a venv, or system env
oh, i do it in venv
my bot.py
import os, discord, urllib.request
from dotenv import load_dotenv
from discord import Intents, Client, Message
from discord_slash import SlashCommand
from discord.ext import commands
from responses import get_response
#Step 1, load TOKEN from discordbot website
#Step 2 Set up
intents = discord.Intents.default()
intents.messages = True #NOQA, pls search yourself
client = discord.Client(intents=intents)
bot = commands.Bot(command_prefix='/',help_command=None)
slash = SlashCommand(client, sync_commands=True)
guild_ids = ['myserverid']
#intents is gives permissions
#You Must set up Discord Client to here then you can operate the bot
#Step 3 Messages Functionality
async def on_ready():
print(f'{client.user} is running now!')
bot_status = discord.Game(name='Setting Bot, But You Can Talk With Me')
#discord.Status, you can do -> online,offline,idle,invisible
await client.change_presence(status=discord.Status.online, activity=bot_status)
async def send_message(message:Message, user_message:str):
if not user_message:
print('(Message was empty because intents were not enabled probably)')
return
is_private = user_message[0] == '?'
if is_private:
user_message = user_message[1:]
try:
response: str = get_response(user_message)
await message.reply(response) if is_private else await message.channel.send(response)
except Exception as e:
print(e)
@client.event
async def on_message(message:Message):
if message.author == client.user:
return
username = str(message.author)
user_message = str (message.content)
channel = str(message.channel)
print(f'[{channel}] {username}: "{user_message}" ')
await send_message(message, user_message)
#Step 4 Main Entry Point
if __name__ == '__main__':
load_dotenv()
TOKEN = os.getenv('TOKEN')
client.run(TOKEN)
print(TOKEN)
and requirements.txt
aiosignal==1.2.0
async-timeout==3.0.1
attr==0.3.2
attrs==22.2.0
chardet==3.0.4
charset-normalizer==3.0.1
discord==1.7.3
discord-py-slash-command==3.0.3
discord.py==2.3.2
emoji==2.10.1
idna==3.6
multidict==4.5.0
python-dotenv==0.20.0
yarl==1.0.0
i install everything in venv,
pip install and do pip freeze > requirements.txt
all i want just build a basic bot, for fun
latest discord.py is 2.x
!pypi discord.py
latest discord. py has slash command included already
ya i know it included but it just say it
> [6/7] RUN pip install -r requirements.txt:
2.560 Collecting aiohttp==3.8.6
2.579 Downloading aiohttp-3.8.6-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (985 kB)
2.628 Collecting aiosignal==1.2.0
2.633 Downloading aiosignal-1.2.0-py3-none-any.whl (8.2 kB)
2.653 Collecting attr==0.3.2
2.661 Downloading attr-0.3.2-py2.py3-none-any.whl (3.3 kB)
2.704 Collecting attrs==22.2.0
2.708 Downloading attrs-22.2.0-py3-none-any.whl (60 kB)
2.735 Collecting chardet==3.0.4
2.741 Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
3.181 Collecting charset-normalizer==3.0.1
3.189 Downloading charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (162 kB)
3.218 Collecting discord==1.7.3
3.224 Downloading discord-1.7.3-py3-none-any.whl (1.1 kB)
3.287 Collecting discord-py-slash-command==3.0.3
3.293 Downloading discord_py_slash_command-3.0.3-py3-none-any.whl (45 kB)
3.346 ERROR: Could not find a version that satisfies the requirement discord.py==2.3.2 (from versions: 0.1.0, 0.2.0, 0.2.1, 0.3.0, 0.3.1, 0.4.0, 0.4.1, 0.5.0, 0.5.1, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.7.0, 0.8.0, 0.9.0, 0.9.1, 0.9.2, 0.10.0, 0.11.0, 0.12.0, 0.13.0, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.15.0, 0.15.1, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.16.7, 0.16.8, 0.16.9, 0.16.10, 0.16.11, 0.16.12, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.2.0, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.4.0, 1.4.1, 1.4.2, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.7.2, 1.7.3)
3.346 ERROR: No matching distribution found for discord.py==2.3.2
------
Error: failed to fetch an image or build from source: error building: failed to solve: executor failed running [/bin/sh -c pip install -r requirements.txt]: exit code: 1
it is i pretty confuse part, it only can found 1.7.3,
u have so many discord imports
:D
does your requirements.txt have both discord==1.7.3 and discord.py==2.3.2? discord is a mirror of discord.py so you should only be installing one of them (if you're installing dpy 2.0 you should remove discord-py-slash-command as well)
install manually your requirements.txt is outdated
oh bruh
It's kinda sad there isn't a built-in way to do that
probably because its fairly fast to make one, ```py
for cog_path in glob.iglob(r'cogs/**/*.py', recursive=True):
cog_module = re.sub(r'\|/', '.', cog_path)[:-3]
await bot.load_extension(cog_module)
there isnt a fixed way to structure cogs it can differ for every project and ur file structure so its usually left to the user
The only reason I avoided using file paths is because of zipapps
which would completely break this
how would it break?
and you're only using it in a cogs folder
oh the bots file as zipapps
Just add a method that maybe will take abs path and a re pattern?
a zipapp would just be one file, so, your bot wouldn't work as one since you're relying on the structure being unzipped
Meh actually it should be on user side, some utils function may sit there on that folder lol that doesnt have setup func (i mean Library can check those technically)
i want it like /pokemon info ability
like that
i alr know how too make it in hybrid commands but not in app i want to make it n app
it hybrid it goes like
@commands.hybrid_group()
async def pokemon:
----
@pokemon.group()
async def info
-----
@info.command()
async def ability()
-----
what help you need
i have this code
import discord.ext
from discord.ext import commands
import discord
TOKEN = "the_token_is_over_here"
client = commands.bot(command_prefix='!', intents=discord.Intents.all())
@client.event
async def on_ready():
print("IT'S ALIVE!")
client.run(TOKEN)
when i run it i get this error
line 9, in <module>
client = commands.bot(command_prefix='!', intents=discord.Intents.all())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'module' object is not callable
what is happening?
commands.Bot *
ok so here is the edited code
import hoodSong
import discord.ext
from discord.ext import commands
import discord
TOKEN = ":>"
client = commands.Bot(command_prefix="$", intents=discord.Intents.default())
@client.event
async def on_ready():
print("IT'S ALIVE!")
@client.command()
async def hi(ctx):
await ctx.send("hello!")
client.run(TOKEN)
but when i run $hi the bot isn't responding
you would need to enable
message_content intent
intents = ...
intents.message_content = True
I have a list of names which are passed to bot.load_extension at startup. Now I would like a command to check whether each cog is loaded. How would I do that? bot.get_cog requires a different kind of name - I could maybe get away with Cog.__subclasses__(), but that is not exactly great.
[cls.__module__ for cls in bot.cogs.values()] does work
turns out extensions are separate from cogs, this is way easier than I thought
anybody know how to do slash commands I have being trying to figure it out all day but there are so many different forms of it I am getting kinda frusturated
generally they're not particularly difficult to write but it depends on what library you're using
discord.py is certainly in need of an official slash commands guide, but they're still working on it
just plain discord.py I assumed it would be easy but I can't find a guide that actually works
right now im about to try discord-py-slash-commands
that one is a few years out of date and isnt supposed to be used since dpy 2.0 released
alright uninstalling that then
or rather the older version of discord-py-slash-command isn't meant to be used with dpy 2.0, however after 3.0.3 it turned into an outdated mirror for the author's rewritten, standalone package, interactions.py
(yes it's much more confusing than it should be, and unfortunately the author didn't add any deprecation warnings)
but anyway this third-party guide can help you out:
https://fallendeity.github.io/discord.py-masterclass/slash-commands/
or to summarize the basics:
- create a CommandTree (commands.Bot comes with one for free)
- define your slash commands using the tree (
@bot.tree.command()) - synchronize your slash commands with discord some way, such as during login or with a command (
bot.tree.sync())
bot = commands.Bot(command_prefix="!!!", intents=...)
@bot.tree.command()
async def hello(interaction: discord.Interaction):
await interaction.response.send_message("Hello world!", ephemeral=True)
await interaction.followup.send("This is a second message!", ephemeral=True)
@bot.event
async def setup_hook():
await bot.tree.sync() # Syncs global slash commands
bot.run(token)```
Oh lord thank you the guides I were following did not mention the bot.tree.sync step im guessing thats a step you would do on bot start up?
that's a usual place to do it, personally i have a prefix command to manually sync when i need to
alright then thank you so much
anyyone know how to make subgroups for groups and then commands for the subgroups using app_commands.group
i want it like /pokemon info ability
A hands-on guide to Discord.py
u can have only at max one level of nesting iirc
i get it nw why it was not working
i can only have one nesting
i had two in the pokemon
Hello, Myself and a friend are trying to set up a new discord bot for a server and our experiencing an issues (paste bin of start to crash log https://pastebin.com/PCLXubpe) it keeps saying Failed building wheel for yarl and something about a file/directory named longinterpr.h not existing. Any help would be amazing.
something is wrong with the package or the service you are using its python version is outdated
It is using Python 3.11.8
what r u using to make your bot
As far as I am aware it was a premade bot by someone else and now we are just trying to actually get it hosted and online
try running it in your computer first
And silly question... how would one do that?
you have python installed in your computer??
I personally dont because I dont actually have the bot files
wait first where you got the code cause these might be a version mentioned
Also unsure, as I said we was just given the files and asked to get it set up
well idk really then
just remove the package from the installing list
which is causing the problem
or just make a bot yourself
I cant figure out which one it is, is the issue
I truthfully havent done Python in nearly 4 years. I have forgotten almost everything so sorry if im a little ya know
This problem seems to have originated from the outdated Cython, try to update it with pip install Cython --upgrade if you can
you can have
group
subcommand group
and command of the subcommand group
this is a 2 level nesting if we count the groups, if you meant this then nvm
hey
i have a discord bot with this code
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if "Heist" in message.content:
await message.reply('<@&1210214496493371412>', mention_author=True)
intents = discord.Intents.default()
intents.message_content = True```
now if i want to add a thing where
if 883086268450349116 is in the message then it cancels and doesnt send the ping
You want the message to be deleted?
yeah check the tut i sent
/a b c is max u can go iirc
u cant really invoke the group so its subcommand then command of subcommand group so just said it like 1 level
You think this would be fine to keep in my on_ready?
@commands.Cog.listener()
async def on_ready(self):
for guild in self.bot.guilds:
try:
self.invites[guild.id] = await guild.invites()
except Exception as e:
print(f"Failed to fetch invites for guild {guild.id}: {e}")```
Im asking would it be fine to keep there, if not then I can use another function aka setup_hook
it won't work in setup_hook since bot.guids requires the cache to be loaded and it's empty before the bot starts
your ideal solution would be using a function with Bot.wait_until_ready function and then proceeding with the code
!d discord.Client.wait_until_ready
await wait_until_ready()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits until the clientโs internal cache is all ready.
Warning
Calling this inside [`setup_hook()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.setup_hook) can lead to a deadlock.
in theory your bot might miss out on newly created invites if it were to be offline for an extended period of time, i.e. the point at which caches are cleared and on_ready is repeated, so if you care about being 100% up to date (or in other words you dont have any way to deal with a missing invite), i think on_ready is fine
new_invites = await member.guild.invites()
old_invites = self.invites.get(member.guild.id, [])
for old_invite in old_invites:
for new_invite in new_invites:
if old_invite.code == new_invite.code and new_invite.uses > old_invite.uses:
inviter = new_invite.inviter```
So you think on_ready will be fine with this whole process?
Ive been told to not put things in on_ready, but thats my only way of doing it right now. So thats why I came in here to ask.
I truly feel like it would be fine to leave this one in on_ready because its just cache n nothing else major imo
and when a invite is made or deleted it runs these 2 things, so the list is always updated when the bot is online.
@commands.Cog.listener()
async def on_invite_create(self, invite):
if invite.guild.id in self.invites:
self.invites[invite.guild.id].append(invite)
else:
self.invites[invite.guild.id] = [invite]
@commands.Cog.listener()
async def on_invite_delete(self, invite):
if invite.guild.id in self.invites:
self.invites[invite.guild.id] = [i for i in self.invites[invite.guild.id] if i.code != invite.code]
stuff like loading extensions or syncing slash commands shouldnt go in on_ready because there's no reason to repeat them when your bot rebuilds its cache, but with invites it might be worthwhile because it means your bot couldnt resume its previous session, meaning it could have missed new/deleted invites
Well by that then, I will keep it in on_ready. I think I should be fine too tbh. I have no thought of it being bad I guess lol
plus i believe they hold references to their guild which will stop receiving updates after on_ready evicts them from the cache, so you might experience sutble issues like outdated/inconsistent data if you happen to use the guild attr from the invite
This should cover everything im pretty sure?
seems fine at a glance, besides the duplicate on_guild_join listener
I fixed it, thats why I changed link lmao
does the command that enables invite tracking also fetch the guild's invites when needed? good place to check if the bot has perms too
alr, I will have to do that
I can just make it check to see if enabled.
it will always get all invites tho when a new member joins if the feature is enabled, then check to see what changed n stuff like that from the new_invites
so it kinda does have a check for that already, but now I just have to make sure the bot has perms
but if you dont have the invites beforehand, there are no old_invites to compare it to
Yes, but it doesn't need old_invite, thats why it checks for all invite codes, so if there is no old invite, it will just read the new invites.
im not sure how the bot would know which invite was used from just the new invites...
it will see which one gained a new use
let me double check tho to see if im correct
You are correct, but I can just handle it to where it wouldn't know the invite code. Which would be fine I think.
else:
log_embed = discord.Embed(
title="Member Joined",
description=f"{member.mention} has joined the server, but I couldn't determine which invite they used.",
timestamp=discord.utils.utcnow(),
color=config.main_color
)
log_embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
log_embed.add_field(name="User ID", value=member.id, inline=False)
log_embed.add_field(name="Account Created",
value=f"{discord.utils.format_dt(member.created_at, style='R')} / {discord.utils.format_dt(member.created_at, style='f')}",
inline=False)
log_embed.add_field(name="Server Joined",
value=f"{discord.utils.format_dt(member.joined_at, style='R')} / {discord.utils.format_dt(member.joined_at, style='f')}",
inline=False)
await webhook.send(embed=log_embed)```
it might be worth mapping the invite code to the uses rather than storing invite objects directly, since you'll need to manually update the count after a member joins anyway
I don't need to update the count, discord does that for you
you just fetch the uses of that code
self.uses: Optional[int] = data.get('uses')
discord doesnt tell you which invite was used when a member joins so dpy has no way of automatically updating its uses, which is kinda why invite tracking is annoyingly complicated
Yes, but when you get the invite, you can see how many uses are on that invite, which discord has a way of tracking uses for you. You just fetch the data off that code
thats what i mean by updating the counts, otherwise old_invites will be out of date
it compares the old invites with new invites, if the new invite has 1 use above old invite code, it assumes it used that invite code, but if it can't determine, it will look for if vanity url, still if no vanity url, it will determine it can't find which code it used, so then it will just send an embed without tracking details n say they joined, n show the user data.
though i guess this isnt necessary cause you have a fresh copy of the invite objects after each join
what happens if you dont update the old invites after a member joins?
After a new member joins, the bot fetches the current invites again, and stores them as the old invites, for the next member that joins, so it can compare the state of the invites before and after each member joins, allowing my bot to determine which invite each member used.
that seems to be missing from your code paste tho
Yes you are correct, but thats what I am going to have to do.
o i thought you were talking about your code as-is from this point, rather than what you were planning to do
oh no
now at the bottom it will do
self.invites[member.guild.id] = new_invites
So then it will update the old invites with the new invites it fetched.
So it always has an updated invite list for that exact guild.
Has anyone built a voice to text bot in python? I found scripty which is open source so I could use it but it's not built with python
I do have to do some more checks on this tho. Which I am working on
ok
no
hey guys new to coding discord bots , how can i raise the timeout before it just says "the application didnt respond" ? my code takes a bit to complete
u need defer it if it takes longer than 3 seconds
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
hey im trying to make a poll command with buttons for people to vote with but it gives me an error:
Ignoring exception in view <poll timeout=180.0 children=5> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='test' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\blaul\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\nextcord\ui\view.py", line 371, in _scheduled_task
allow = await self.interaction_check(interaction)
File "c:\Users\blaul\Desktop\admin helper\main.py", line 2039, in interaction_check
return interaction.user == self.user
AttributeError: 'poll' object has no attribute 'user'
I even tried asking chat gpt but it didnt help at all... It only tried destroying the code like usual
class poll(nextcord.ui.View):
def __init__(self, options, message):
super().__init__()
self.options = options
self.message = message
async def on_button_click(self, button, interaction):
self.clear_items()
for option in self.options:
if button.label == option:
await interaction.response.send_message(f'You voted for {option}!', ephemeral=True)
break
async def interaction_check(self, interaction):
return interaction.user == self.user
@bot.slash_command(name="poll", description="Create a poll with buttons")
async def poll(ctx, question: str, option1: str, option2: str, option3: str = None, option4: str = None, option5: str = None):
options = [option for option in (option1, option2, option3, option4, option5) if option is not None]
if len(options) < 2 or len(options) > 5:
await ctx.send("Please provide between 2 to 5 options for the poll.")
return
embed = nextcord.Embed(title="Poll", description=question, color=nextcord.Color.blue())
for i, option in enumerate(options):
embed.add_field(name=f"Option {i+1}", value=option, inline=False)
view = poll(options, ctx.message)
for option in options:
view.add_item(nextcord.ui.Button(style=nextcord.ButtonStyle.primary, label=option))
await ctx.send(embed=embed, view=view)```
pass the user object as an attribute of the view
well now that error is gone and i think i did it correctly but the buttons dont send a the message...
class Poll(nextcord.ui.View):
def __init__(self, options, user):
super().__init__()
self.options = options
self.user = user
async def on_button_click(self, button, interaction):
self.clear_items()
for option in self.options:
if button.label == option:
await interaction.response.send_message(f'You voted for {option}!', ephemeral=True)
break
async def interaction_check(self, interaction):
return interaction.user == self.user
@bot.slash_command(name="poll", description="Create a poll with buttons")
async def create_poll(ctx, question: str, option1: str, option2: str, option3: str = None, option4: str = None, option5: str = None):
options = [option for option in (option1, option2, option3, option4, option5) if option is not None]
if len(options) < 2 or len(options) > 5:
await ctx.send("Please provide between 2 to 5 options for the poll.")
return
embed = nextcord.Embed(title="Poll", description=question, color=nextcord.Color.blue())
for i, option in enumerate(options):
embed.add_field(name=f"Option {i+1}", value=option, inline=False)
view = Poll(options, ctx.user)
for option in options:
view.add_item(nextcord.ui.Button(style=nextcord.ButtonStyle.primary, label=option))
await ctx.send(embed=embed, view=view)```
don't think on_button_click exists as an event
you should add that function as a callback of the button itself
thanks
https://youtu.be/KIPJeiUweqM?si=e_6abtnI2zpU9gFe
If any beginner want mute cmd
In this Discord.py tutorial, we'll learn how to implement a Mute command using Discord's Python library. Muting users can be a crucial feature for managing voice channels effectively, especially in larger servers. By following along with this step-by-step guide, you'll understand how to code a Mute command using Discord.py's Cog.
๐ดSubscribe t...
Me when there's the built-in /timeout command
such a great guide ๐
Gotta love that random red arrow
Hey!
How do I make something in the likes of:
async def cmd(...):
"""description which will be default for the help for this command"""
if not var:
await send aboves default help function here
Or is this something that is done automatically by discord when not all vars are provided?
for slash commands? if the parameter is required then yes, they cant trigger the command without it
This is prefix command. (for now anyway)
in that case, dpy raises a MissingRequiredArgument exception which you can catch in an error handler and send a message based on what was missing
!d discord.ext.commands.MissingRequiredArgument
exception discord.ext.commands.MissingRequiredArgument(param)```
Exception raised when parsing a command and a parameter that is required is not encountered.
This inherits from [`UserInputError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.UserInputError)
I'd like to access the default help for the command. which should be created by the docstring.
then you can pass the command object contained in that exception the context to ctx.send_help()
And what is the command object?
I'm using cogs.
@commands.command(name="cmd")
async def cmd(self, ctx: commands.Context, *, message: str | None) -> None:
if not message:
ctx.send_help() # just this?
ctx.command refers to the Command instance that the context is invoking, that being cmd in that example
okay.
so
ctx.send_help(ctx.command) would do the trick? ๐
(testing now)
personally i would still suggest using an error handler if you need to do this for multiple commands so you dont need to repeat the same conditions
dont forget to await it too
fyi it can be as simple as: py @commands.Cog.listener() async def on_command_error(self, ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send_help(ctx.command) else: raise error # show other error messages in terminal
Okay I see. thanks!
That works. Now I just need to figure out how discord parses that doc string
to my knowledge its less sophisticated than the parsing done for slash commands, but you can see the default implementation here
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ext/commands/help.py#L1469-L1477
parameter-specific documentation is handled via writing parameter() defaults
https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.parameter
oh the snippet i linked earlier was for the MinimalHelpCommand, not the DefaultHelpCommand
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ext/commands/help.py#L1146-L1222
discord/ext/commands/help.py lines 1221 to 1222
if self.show_parameter_descriptions:
self.add_command_arguments(command)```
To learn more about how to create custom help commands in discord.py by subclassing the help command, please see this tutorial by Stella#2000
Thanks!
i belive just raise would be enough
depends on whether on_command_error runs inside an except block, but given that the event is dispatched and so runs in a separate asyncio task, i dont think that shorthand works
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/ext/commands/core.py#L643-L650
discord/ext/commands/core.py lines 643 to 650
try:
if cog is not None:
local = Cog._get_overridden_method(cog.cog_command_error)
if local is not None:
wrapped = wrap_callback(local)
await wrapped(ctx, error)
finally:
ctx.bot.dispatch('command_error', ctx, error)```
hmm let me try it out just for curiosity
this is what i got ```py
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=commands.when_mentioned, intents=discord.Intents.default())
@bot.event
async def on_command_error(ctx, error):
raise
@bot.command()
async def hello(ctx, name):
await ctx.send(f"Hello {name}!")
bot.run(...)
py
Traceback (most recent call last):
File ".venv\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "test.py", line 8, in on_command_error
raise
RuntimeError: No active exception to reraise```
in theory it should work for the local and cog handler, but im too lazy to test that
curiously that try/finally block doesnt include execution of the local handler, so i guess the event never gets dispatched if the local handler fails?
well i guess it worked in other framework then
could be
Error: ```raceback (most recent call last):
File "main.py", line 41, in <module>
bot.load_extension(f'cogs.{filename[:-3]}')
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/disnake/ext/commands/common_bot_base.py", line 523, in load_extension
self._load_from_module_spec(spec, name)
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/disnake/ext/commands/common_bot_base.py", line 455, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
disnake.ext.commands.errors.ExtensionFailed: Extension 'cogs.utility_commands' raised an error: NameError: name 'bot' is not defined
Code: ```py
intents = discord.Intents.all()
bot = commands.Bot(
command_prefix='?',
intents=intents,
case_insensitive=True
)
bot.remove_command("help")
# Load Cogs
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
Library - Disnake
Can anyone help?
the error is from a file that you didnt show
# Import Disnakes
import disnake as discord
import disnake
from disnake import Webhook
from disnake.ext import commands, tasks
# .env Imports
from dotenv import load_dotenv
import os
# psutil
import psutil # STATS
# Default Imports
import toml # EVAL
import textwrap # EVAL
import traceback # EVAL
import asyncio
from datetime import datetime
import datetime # Days Commands
import time # STATS
# DB
import aiosqlite
# Functions
from functions import *
class utility_commands_cog(commands.Cog):
def __init__(self, bot):
self.bot = bot
def setup(bot):
bot.add_cog(utility_commands_cog(bot))```
well from this code i can see it shouldnt raise that error
so you are not showing something or its wrong file
can anyone help me private?
why not here?
because i m German and idk how to say it so i will create a Bot with Python but the bot wouldnt go online and idk why
then send code and errors you are getting if any
Ok wait
import discord
from discord.ext import commands
import os
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')
my_secret = os.environ['DISCORD_TOKEN']
all what i got now
you need to actually start the bot using bot.run(token)
nope
Mh ok then what i shpuld do now?
doesnt work what? you get an error? or what happens doesnt work tells me nothing
yeah its an error wait
Traceback (most recent call last):
File "/home/runner/DCE/main.py", line 13, in <module>
bot.run(token)
NameError: name 'token' is not defined. Did you mean: 'open'?
but if i write the Token there anyone can see it
who said you have to write it here
where should i?
in your code?
but you are already using environment variables
you literally have the token in a variable already
just need to pass it to bot.run()
.. what doesnt work? what did you do
import discord
from discord.ext import commands
import os
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='>', intents=intents)
@bot.command()
async def ping(ctx):
await ctx.send('pong')
bot.run()
i write exact this but it doesnt work
you have a variable my_secret that has a token
and you have to put it inside bot.run()
bot.run(my_secret) ?
try
nope the same error
what error
Traceback (most recent call last):
File "/home/runner/DCE/main.py", line 13, in <module>
bot.run(my_secret)
NameError: name 'my_secret' is not defined
in the code you sent before you had this variable
yeah but then you say i didnt have to write the last part
i dont remember saying that
just put back that variable
done and now?
try to run it?
Traceback (most recent call last):
File "/home/runner/DCE/main.py", line 13, in <module>
bot.run = os.environ['my_secret']
File "/nix/store/xf54733x4chbawkh1qvy9i1i4mlscy1c-python3-3.10.11/lib/python3.10/os.py", line 680, in getitem
raise KeyError(key) from None
KeyError: 'my_secret'
i dont know from where did you get bot.run = os.environ but yeah i would recommend learning python before making a bot
cause you clearly have no idea what you are doing sorry.
import pyttsx3
import speech_recognition as sr
engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
print(voices[0].id)
engine.setProperty('voices', voices[0].id)
def speak(audio):
engine.say(audio)
print(audio)
engine.runAndWait()
def takecommand():
r = sr.Recognizer()
with sr.Microphone(device_index=0) as source:
print("listening....")
r.pause_threshold = 1
audio = r.listen(source,timeout=1,phrase_time_limit=5)
try:
print("Recognizing...")
query = r.recognize_google_cloud(audio, language='en-in')
print(f"user said: {query}")
except Exception as e:
speak("say that again please...")
return "none"
return query
if name == "main":
takecommand()
speak("This is advanced jarvis")
"C:\Program Files\Python312\python.exe" C:\Users\vvish\PycharmProjects\pythonProject\jarvis.py
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0
listening....
Traceback (most recent call last):
File "C:\Users\vvish\PycharmProjects\pythonProject\jarvis.py", line 21, in takecommand
audio = r.listen(source,timeout=1,phrase_time_limit=5)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\vvish\AppData\Roaming\Python\Python312\site-packages\speech_recognition_init_.py", line 465, in listen
assert source.stream is not None, "Audio source must be entered before listening, see documentation for AudioSource; are you using source outside of a with statement?"
AssertionError: Audio source must be entered before listening, see documentation for AudioSource; are you using source outside of a with statement?
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "jarvis.py", line 35, in <module>
takecommand()
File "jarvis.py", line 18, in takecommand
with sr.Microphone(device_index=0) as source:
File "AppData\Roaming\Python\Python312\site-packages\speech_recognition_init_.py", line 189, in exit
self.stream.close()
^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'close'
Process finished with exit code 1
Can you grab a channel using get_channel or fetch_channel from the command context?
@commands.hybrid_command(name="suggestion-approve", description="Approve a suggestion created by the community")
async def suggestapprove(self, ctx: Context, suggestionid: str):
channel = bot.get_guild(1208279263438966875).get_channel(1211381701561942108)
message = await channel.fetch_message(result[4])
await message.edit(embed=embed)
The above code genrates the below error
Command 'suggestion-approve' raised an exception: AttributeError: 'NoneType' object has no attribute 'get_channel'
I can't remeber if it either of the below is possible
channel = ctx.get_channel(1211381701561942108)
channel = ctx.get_guild(1208279263438966875).get_channel(1211381701561942108)
if you want to access the guild or channel the command was invoked in you can use ctx.guild or ctx.channel
can someone help me
guild is None
can someone help me fix this?
send full traceback here as text
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
A guide on fixing verification of an SSL certificate.
try this but i doubt this is the case
hold on a sec, I have an idea for how else to fix the problem
I'll be back in a few minutes
I fixed it I think, I just had to connect my laptop to ethernet because for some reason its Wifi turns off when I close the screen and my discord bot script was running while the screen was off
oop, no nevermind
this isn't strictly related to python but does anybody know how to make my laptop's wifi stop turning off when I close the screen?
Google it would be your best go to
I don't even know what to say
Try this
intents = discord.Intents.default()
intents.members = True
intents.message_content = True```
@mossy jacinth
he already has .all() enabled
Already tried that and it still says the same thing
i dont know if i did something wrong in the code
you dont pass intents ?
bruh i somehow moved that down there ๐ญ
i think i selected it and accidentally dragged it
like this maybe but i hope thats the issue ๐ญ
another question ๐ญ is there a way to send a message instead of showing "The application did not respond"?
use await interaction.response.send_message()
what do you mean?
why i can't get message from server callback pls help
Use them
wdym
what are the limits of discord.User, discord.Role and discord.Channel?
like for example, am i able to only display the roles a user has, or a channel within a specific category, or is it limited to all the channels a user is able to see and all roles?
for interaction obviously
wdym? this question doesn't make much sense, what are you trying to do
how could i make an image cycle thru colours like this but like in discord.py
with the use of pil or smthing
well u can create a filter or tint image with that shade of colour and adjust the opacity value and then do an alpha composite operation
original image + tint image
you would do this multiple times cycling through colours and store the frames to create a gif
perhaps once I get back home
thanks
hmm shiba?
Dont you hate it, but love it at the same time, that you figure out the answer yourself while trying to formulate a proper question..?
this is how rubber duck debugging works
Yeah it's great!
Im looking for someone to talk me through syncing commands to discord. If someone has some time..?
There are a couple of opinions about this topic. Some with a synced flag in the setup_hook. I've decided I dont want to do this and I made a command to "manually" sync the commands only when I have to.
Now that my bot is only in 1 guild there;s no real reason to sync globally as far as I understand how that works anyway. So I've made a command for it in a Cog which does this.
synced = await self.bot.tree.sync(guild = ctx.guild)
According to online you can then return len(synced) to see how many commands are synced, however it's always 0 and it doesnt seem to actually give me the commands in discord?
Im trying to sync to guild only as i've heard it's faster than global..?
Addressing that last statement. It is a misconception from a time when it was true, when slash commands were released, a couple of years ago.
For the fact that it is always 0, are the commands guild commands? You need to either a) add @app_commands.guilds(...) atop each command, or b) tree.copy_global_to(guild) before you sync.
And yeah, you generally should not auto-sync.
Thanks for replying! ๐
I think I need to do options b) they are not guild specific commands. They are "just" @app_commands.command() in a MyGroup(commands.GroupCog)
However I can never find said "tree" when inside the cog, or dont know how to access it.
do I do:
self.bot.tree.copy_global_to(guild)
then:
synced = await self.bot.tree.sync(guild = ctx.guild)
?
yes. But then again, I do think it's better to sync globally since there's no difference
Okay, so how would I sync globally?
Not passing guild=... To sync
right xD
:P
And in your XP, how long does it take for discord to reflect changes?
I've read "up to an hour" for global commands.
Which was the reason why I looked into syncing to guild only as it's supposed to be quicker?
Instant. It doesn't take up to an hour anymore,
Addressing that last statement. It is a misconception from a time when it was true, when slash commands were released, a couple of years ago.
Okay. Then still im doing something wrong I think.
Oeh!
I got it! ๐
guild = ctx.guild self.bot.tree.copy_global_to(guild = guild) synced = await self.bot.tree.sync(guild = guild)
Works a charm to load to guild in any case.
Like you said, instant!
Thank you so much! Been getting headaches about this for a long time. ๐
No problem
Back to testing. ๐ซก
๐ซก
Hi guys, can someone help me correct this error that sometimes occurs
2024-02-22 21:03:41 ERROR discord.client Ignoring exception in on_member_update
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/listen.py", line 147, in on_member_update
row = connect_db(guild_id, "SELECT channel_id FROM log_moderation WHERE guild_id = %s;")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/cogs/listen.py", line 13, in connect_db
cursor.close()
File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/cursor_cext.py", line 541, in close
self._cnx.handle_unread_result()
File "/home/container/.local/lib/python3.11/site-packages/mysql/connector/connection_cext.py", line 990, in handle_unread_result
raise InternalError("Unread result found")
mysql.connector.errors.InternalError: Unread result found```
@commands.Cog.listener()
async def on_member_update(self, before, after):
guild_id = before.guild.id
row = connect_db(guild_id, "SELECT channel_id FROM log_moderation WHERE guild_id = %s;")
if row is None:
return
channel_id = row[0]
channel_send = before.guild.get_channel(channel_id)
if len(before.roles) < len(after.roles):
newRole = next(role for role in after.roles if role not in before.roles)
if before.roles != after.roles:
logs = [log async for log in after.guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update)]
logs = logs[0]
embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
embed.add_field(name = "Role added :", value = newRole.mention, inline=False)
embed.add_field(name = "Modified by:", value = logs.user.mention, inline=False)
embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
await channel_send.send(embed=embed)
elif len(before.roles) > len(after.roles):
oldRole = next(role for role in before.roles if role not in after.roles)
if before.roles != after.roles:
logs = [log async for log in before.guild.audit_logs(limit=1, action=discord.AuditLogAction.member_role_update)]
logs = logs[0]
embed = discord.Embed(title = f"Member roles updated", description = f"{before.mention} Member updated", color=discord.Color.dark_purple())
embed.add_field(name = "Role removed :", value = oldRole.mention, inline=False)
embed.add_field(name="Modified by:", value = logs.user.mention, inline = False)
embed.add_field(name = "Account created :", value = before.created_at.strftime('%d %B %Y at %H:%M (UTC +0)'))
await channel_send.send(embed=embed)
def connect_db(guild_id, query):
connection = mysql.connector.connect(host='', database='', user='', password='')
cursor = connection.cursor()
cursor.execute(query, (guild_id,))
result = cursor.fetchone()
cursor.close()
connection.close()
return result```
- You need to have only ONE connection per application, not create one every time you need to make a request
- You need to use async version of your db wrapper
ok, i go to try with a waiting queue for execute request
My bot is on a multi server so he create a lot of request to the db
Yes and you are handling them in a crazy inefficient way
Do this
So i need to connect to the database only when i start the bot ?
technically internally async is sorta like that queue since there's event loop but that's not what I meant
Exactly
And store it as attribute of bot subclass
But if the bot doesn't send any queries to the database for a while, won't that break the connection ?
Then close in Bot.close() override
It won't
If your db wrapper supports pools it's better to use them however
But still one pool per app
i use MySQL
This shows basics of async mysql https://dev.mysql.com/doc/connector-python/en/connector-python-asyncio.html
Quick googling
And this about basics of pooling https://dev.mysql.com/doc/connector-python/en/connector-python-connection-pooling.html
It operates same way as connection except it creates connections for you as they are needed
anyone able to help me make it so my webhook sends messages, it only gives me a output in VSC
import requests
import time
WEBHOOK_URL = "no"
def send_discord_message(message):
payload = {
"content": message
}
headers = {
"Content-Type": "application/json"
}
response = requests.post(WEBHOOK_URL, json=payload, headers=headers)
if response.status_code == 204:
print("Webhook message sent successfully.")
else:
print("Failed to send webhook message. Status code:", response.status_code)
def check_username_availability(username):
url = f"https://auth.roblox.com/v1/usernames/validate?birthday=1970-01-01T00:00:00.000Z&context=UsernameValidationContext&username={username}"
response = requests.get(url)
data = response.json()
if data.get("valid") == False:
send_discord_message(f"Taken: {username} is taken on Roblox.")
elif data.get("valid") == True:
send_discord_message(f"@everyone {username} is available!")
elif data.get("error"):
if data["error"]["message"] == "Inappropriate":
send_discord_message(f"Inappropriate: {username} is not appropriate for Roblox.")
else:
print("Unexpected response:", data)
def main():
username = "nopnref"
while True:
check_username_availability(username)
time.sleep(0.01)
if __name__ == "__main__":
main()
also, dont take the username nopnref i want webhook to send msg if valid
Hello, I am a beginner and am currently looking for a better hoster than Replit, can someone help me?
use visual studio code
And that means, as I said, I'm still a beginner.
webhook = "link"
data = {
"content": f"Message Webhook",
"embeds": [{
"title": "Webhook",
"description": "This webhook",
"color": 16732345,
}],
"username": "test",
"avatar_url": "https://i.imgur.com/44N46up.gif"
}
response = requests.post(webhook, json=data)```
hi guys, what databases u are using?
I use PostgreSQL for pretty much everything, very robust, industry-grade, and easy to set up
SQLite is good if you want something more lightweight
SQLite will fit your needs regarding beginnary and ease on use
anyone know how to get a users default avatar if they don't have one
avatar = user.avatar.url if user.avatar else f"https://cdn.discordapp.com/embed/avatars/{int(user.discriminator) % 5}.png"
I thought it all relied on a user id
use user.display_avatar.url
works for default avatars
avatar = user.display_avatar.url no need for other endpoints urls
by the way, there is also User.default_avatar that does that second for you. But yeah, there's also display_avatar that does that whole thing you're doing for you 
How can I get all messages from a channel?
I remember there's a way to do it with list comp
Not sure if I'm doing it wrong.
history = [message.content async for message in channel.history()]
print(len(history))
# always only printing 100
Do I have to append the messages to a seperate list and iterate by chunks
maybe im slow but I did that at first and it wasn't working
I forgot the error but decided to try a work around
but thx @split vessel @pale zenith
yeah well user.display_avatar.url will do everything for you including custom avatars and default ones
that's because the default limit is 100, set to None as stated
Setting to None only returned 100 still
Show your current code
async def extract(interaction: discord.Interaction, channel: discord.TextChannel) -> None:
if channel is not None:
history = [message.content async for message in channel.history(limit=None)]
print(len(history))
else:
await interaction.response.send_message("**Ensure you specify a channel!**")
Buddy he is asking for a "hoster" not an editor
Is that hoster or editor?
Link?
Thx
That
that's an editor
dog
Guys! I encountered a problem. My code doesnt mention anything about 'help' command.. But still upon calling it, it works
Like this. I just wanted to know if this a default behaviour of discord package
it is the built in help command
How to disable it?
pass help_command=None to your bot
where?
discord.ext.commands.Bot
You need to pass the help_command kwarg in the Bot constructor.
somewhere in the file there should be
_ = commands.Bot(...., help_command=None)
keep everything else the same except adding that
Else?
You overwrite the imported commands from the discord.py module.
why doesnt the purge command work?..
it worked before, i added the verify thing now it doesnt work
from .akinator_buttons import AkinatorButtons
ImportError: attempted relative import with no known parent package
How can i fix this?
import asyncio
import os
import random
import discord
from discord.ext import tasks
from dotenv import load_dotenv
load_dotenv() # load all the variables from the env file
bot = discord.Bot()
characters = [
[
"1",
"https://cdn.discordapp.com/avatars/1095746248599949444/0cf827a34a40515b93fbd5715225adc4.png"
],
[
"2",
"https://cdn.discordapp.com/avatars/433270158912389130/0f5a17577fa60bb205ddb50411fe9ed9.png"
],
]
@bot.slash_command(name="ping", description="check latency")
async def ping(ctx):
await ctx.respond(f"Pong! {bot.latency}s")
@tasks.loop(seconds=20)
async def loop():
n = random.randrange(0, 2)
chnl = bot.get_channel(514087784026210305)
char = characters[n]
embed = discord.Embed(
title="relic",
description="A wild relic appeared!",
color=discord.Color.blue(),
)
embed.set_image(url=char[1])
def check(m):
# check message content ignoring case and extra spaces
return m.content.lower().strip() == char[0].lower() and m.channel == chnl
try:
await chnl.send(embed=embed)
react = await bot.wait_for('message', check=check, timeout=400)
await chnl.send(f"@{react.author.id}, you caught **{char[0]}**!")
except asyncio.TimeoutError:
await chnl.send(f"No one caught {char[0]}")
@bot.event
async def on_ready():
if not loop.is_running():
loop.start() # If the task is not already running, start it.
print(f"{bot.user} is online!")
bot.run(os.getenv('TOKEN'))
this code is able to send the characters, but i cant collect them for some reason, anyone knows why?
also the 20 seconds is temporary, when the bot is finished il set it to like 10 minutes
You would need the message content intent
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
i have that enabled
in the bot settings
but do i need to add it to the code?
yes, as per the above example (technically meant for discord.py but should be compatible with pycord)
๐
My bot suddenly lost its embed colour, is this normal?
that's due to Discord not the bot
Oh
happening to me too
@discord.ui.button(label="Approve", style=discord.ButtonStyle.green, custom_id="approveBtn")
async def approveBtn(self, interaction: discord.Interaction, button: discord.ui.Button):
## get the field from the embed ## ex01x
code = interaction.message.embeds[0].fields[0].value
## update the database ## ex01x
vouchStorage.update_one({"_id": code}, {"$set": {"status": "approved"}})
## send a message to the user ## ex01x
try:
user = bot.get_user(vouchStorage.find_one({"_id": code})["target"])
except Exception as e:
print(e)
embed = discord.Embed(description=f"Your vouch with the ID `{code}` has been approved.", color=0x2ecc71)
embed.set_author(name='Vouch Notification System')
embed.set_footer(text="Made by Doare | Kudos!")
await user.create_dm()
try:
await user.send(embed=embed)
except:
pass
## delete the message ## ex01x
await interaction.message.delete()
I'm getting a 'NoneType' object is not subscriptable error due to me trying to use the bot.get_user
I've tried providing the class with self.bot but that did not work, is there a fix or an alternative way for this to work?
Weird ah
idk new embed styling or something but it looks shit
you can even notice that things are not sorted as how they were before not only the colors fading away
Rip
Anyone able to help?
Is there anyone here taking paid work at all? Looking for a discord Python bot developer:)
Unfortunately, we do not allow any kind of paid work on this server including the solicitation of said work. Sorry!
No worries ๐
Ikr
Let's make a petition to discord to stop being goofy ahh
you must also define intents into the discord.Client
Client = discord.Client(intents=intents)
Thanks
no, you only use commands.Bot or discord.Client, not both, you should set message_content intents, messages intents is different, its a default intents where you receive the message object itself.
๐ค
" ๐ค " ๐ค
A hands-on guide to Discord.py
thank ku
What should i do?
user....
O yea
@bot.slash_command(name="collection", description="check your Boardex collection!")
async def collection(ctx):
embed = discord.Embed(
title="Boardex collection",
description=f"{ctx.author.name}'s relics **(a lower number is more rare)**",
color=discord.Color.blue(),
)
for cx in characters:
ch = unidecode(cx[0].replace(" ", "_").replace(".", "").lower())
c.execute(f"SELECT {ch} FROM users WHERE id = {ctx.author.id}")
v = c.fetchone()[0]
if v is None:
embed.add_field(name=f"{cx[0]} (Rarity: {cx[2]})", value=f"You have 0 {cx[0]}(s)")
else:
embed.add_field(name=f"{cx[0]} (Rarity: {cx[2]})", value=f"You have {v} {cx[0]}(s)")
await ctx.respond(embed=embed)
this code works but it breaks discords message limit, how could i divide it into pages of 15 characters?
buy nitro to bot
๐
i meant like, dividing the messages
because idk how to make the for loop stop at 15 characters, send it and start again
Oh, idk. I am just a newbie in python
async def on_voice_state_update(member, before, after):
if after.channel and after.channel.name == "Join to Create": # Check if member joined "Join to Create" channel
guild = member.guild
channel_name = f"{member.display_name}'s Channel"
# Check if a channel with the same name already exists
existing_channel = discord.utils.get(guild.channels, name=channel_name)
if existing_channel:
await member.send(f"A channel with your name already exists.")
return
overwrites = {
guild.default_role: discord.PermissionOverwrite(connect=False),
guild.me: discord.PermissionOverwrite(connect=True),
member: discord.PermissionOverwrite(connect=True)
}
try:
# Create voice channel
new_voice_channel = await guild.create_voice_channel(name=channel_name, overwrites=overwrites, category=after.channel.category)
await member.move_to(new_voice_channel)
# Create text channel
new_text_channel = await guild.create_text_channel(name=channel_name, overwrites=overwrites, category=after.channel.category)
await member.send(f"Your channels '{channel_name}' have been created!")
except discord.Forbidden:
await member.send("I don't have permission to create channels.")
if before.channel and before.channel.name.startswith(member.display_name) and len(before.channel.members) == 0:
# Delete voice channel
await before.channel.delete()
# Find and delete corresponding text channel
text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
if text_channel:
await text_channel.delete()```
how do i also delete the text channel when the custom voice channel has been deleted?
aren't you doing that already?
So you want a pagination that will only allow 15 fields per page?
also I don't know what library you are using, but it looks somewhat similar to discord.py, so that shouldn't be much of a problem
you can do something like
divided_characters = [characters[i : i + 15] for i in range(0, len(characters), 15)]
to make a new list with sublists and each sub list containing 15 characters
@slate swan
its not working ;(
yeah that would seem like the solution for strings, but it seems that they want to make pagination based on fields (15 embed fields per page)
any errors? anything at all?
so
when the voice channel gets deleted, i also want the text channel to get deleted
the voice channel gets deleted, but the text channel isnt (this is the problem)
this is the code right?https://paste.pythondiscord.com/V4GQ
just its easier for me to view it that way
ye this is it
so this part gets triggered ```py
if before.channel and before.channel.name.startswith(member.display_name) and len(before.channel.members) == 0:
# Delete voice channel
await before.channel.delete()
# Find and delete corresponding text channel
text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
if text_channel:
await text_channel.delete()```
and the voice channel gets deleted
but the text one doesn't right?
well they said they wanted to show 15 characters per page (I personally don't think that would still be within the message limit) but they can divide the characters list into sublists of 15 characters each, and then loop through the sublists, and then the items of the sublists, while making a new embed for each sublist and then supplying the list of all the embeds to a paginator class (that's what I do atleast)
yeah we should wait for their response, that'll make it more clear on what exactly they want
mhm
oh I see the problem now
what is it??
in here to search: text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
you use the before.channel.name
but that is done after deleting the before.channel
ohhh
hmm
you could just switch places
if before.channel and before.channel.name.startswith(member.display_name) and len(before.channel.members) == 0:
text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
# Delete voice channel
await before.channel.delete()
# Delete corresponding text channel
if text_channel:
await text_channel.delete()
like this ๐
Much!?
yeah what does that mean
That's pretty self-explanatory
and much more
may I ask if you have previous experience with python, or coding in general?
you pasted my code weirdly I think
nah, i can fix it
just saying what he said needed a fix, or just discord intended it bad xd
maybe he said it good just it pasted bad in vscode
pretty sure u forgot to indent it
yeah
@primal wave check the hosting thread of this channel
you can find useful info in the pins there
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "C:\Users\userDownloads\veta-discord\main.py", line 275, in on_voice_state_update
await text_channel.delete()
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\abc.py", line 822, in delete
await self._state.http.delete_channel(self.id, reason=reason)
File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 741, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10003): Unknown Channel
alr
or the channel already got deleted
Channel channel XD
bcs sadly discord doesnt allow text channels to have space and '
and -'s
yeah :(
well I suppose that can be solved easily
how??
the .name should be str but lemme check the docs
yeah its str
so in the search instead of before.channel.name do some filtering with before.channel.name.lower().replace(' ', '-')
and the voice channel name should turn into the text channel name
it should be here
right?
cuz i have more before.channel.name
text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
# Delete voice channel
await before.channel.delete()
# Delete corresponding text channel
if text_channel:
await text_channel.delete() ```
non modified code, as u can see i have more before.channel.name, but what you are saying its supposed to be on the first line right?
so the code should look like this:
text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
# Delete voice channel
await before.channel.delete()
# Delete corresponding text channel
if text_channel:
await text_channel.delete()```
no in the search
wdym?
nono, when you search the channel
ohh
... = discord.utils.get(..., name=before.channel.name.lower().replace(' ', '-'))
so at the name=before.channel.name (2nd line)
text_channel = discord.utils.get(member.guild.channels, name=before.channel.name)
yee, thanks bro
lemme test it
no error, but no delete..
try printing it before deleting
btw
print(text_channel)
ok ok
oh ' gets removed too
ye
so need to add .replace("'", "")
like that ... = discord.utils.get(..., name=before.channel.name.lower().replace(' ', '-').replace("'", ""))
I'm afraid it won't in the future
because people are weird and they can put weird stuff in their nicknames
and the channel name is based on their nickname
i will also add things for those
so that might break it at some point
by things i mean replace
alright then, good luck
thanks :D
could also use regex
hey guys, i made warn command and i warned myself, the warn is not saving in database
that is going to require a little more than what you sent to solve, at least send some code
Okay
so.. any code?
how do you save the data to the database? which database do you use?
sqlite 3
so the sqlite3 library?
ye
@commands.has_permissions(kick_members=True)
async def warn(ctx, user: discord.Member, *, reason: str):
c.execute('SELECT count FROM warnings WHERE user_id=?', (user.id,))
result = c.fetchone()
if result is None:
c.execute('INSERT INTO warnings VALUES (?, 1)', (user.id,))
else:
c.execute('UPDATE warnings SET count=? WHERE user_id=?', (result[0] + 1, user.id))
await ctx.send(f'{user.name} has been warned.')
conn.commit()
@bot.command()
async def warns(ctx, user: discord.Member = None):
if not user:
user = ctx.author
# ะฟะพะปััะฐะตะผ ะบะพะปะธัะตััะฒะพ ะฟัะตะดัะฟัะตะถะดะตะฝะธะน ะดะปั ะฟะพะปัะทะพะฒะฐัะตะปั
c.execute("SELECT warns FROM warns WHERE user_id=? AND guild_id=?", (user.id, ctx.guild.id))
result = c.fetchone()
if result is None:
warns = 0
else:
warns = result[0]
# ะพัะฟัะฐะฒะปัะตะผ ัะพะพะฑัะตะฝะธะต ั ะบะพะปะธัะตััะฒะพะผ ะฟัะตะดัะฟัะตะถะดะตะฝะธะน
embed = discord.Embed(title=f'Warns for {user.name}', color=0x00ff00)
embed.add_field(name='Warns', value=warns, inline=False)
await ctx.send(embed=embed)```
ok, I would recommend using an async library, but for starters that's okay I guess
ok nice thx
what are c and conn?
idk, i found this code on internet
actually conn is a connection and c is a cursor I suppose
Ohh
๐ good job man

I bet russian tutorials are good asf ๐
maybe lol
I haven't seen a good one in english
nor in russian lol
anyway, you should note that if you are using code, you should understand what and how it is doing
it is not a secret that developers copy paste a lot, but not understanding what your code does is quite... not nice
now.. back to solving the problem
I suspect that the connection is set up improperly
@empty ferry can you send the code where it says conn = ...?
# creating a connction to database
conn = sqlite3.connect('warnings.db')
c = conn.cursor()```
so, it does create a warnings.db file somewhere in the project folder right?
show your database structure
yeah that would make sense
right there....
ig...
that doesn't show me the database structure
no that's not the structure we want
show me your tables in the database
the tables, their columns
I havent created them.. so should i create them?
obviously you should, without tables there's nowhere to store the data
yeah phpmyadmin would for mysql
thanks, now going to make them 
sqlite has a download page on their website, but I would recommend you create the tables in the code using the sql syntax, like conn.execute("CREATE TABLE IF NOT EXISTS warns (...);")
use that as reference ^^
downloaded already
and sqlite dll win x64 folder
yeah
change the table name, and change the columns to what you need.
I'm surprised the tutorial you read doesn't give that to you
show me what it looks like
no. you need to change your query to be correct, change it to have the table name 'warnings' and then change the column names
oh
CREATE TABLE IF NOT EXISTS warnings (
user_id INTEGER,
count INTEGER,
PRIMARY KEY (user_id)
);
```something like this would probably work for you just fine
the reason?
lol
oh yeah reason too i forgot that
there are no arrays in sqlite tho
?
so you'd have to unprimary key the user_id
ah i didn't know that, thats aids
do you need email in your warnings system?
and you also might have to change it from an integer to something else because im pretty sure userid's are too long to store them as an integer
o yea, forgot abt it
Cool story bro!
?
yeah, in postgres I have to use BIGINT
snipy hey!!!
long time no see
import sqlite3
# Connecting to sqlite
# connection object
connection_obj = sqlite3.connect('warnings.db')
# cursor object
cursor_obj = connection_obj.cursor()
# Drop the GEEK table if already exists.
cursor_obj.execute("DROP TABLE IF EXISTS GEEK")
# Creating table
table = """ CREATE TABLE GEEK warnings (
Email *hidden* (255) NOT NULL,
First_Name ascii(25) NOT NULL,
Last_Name(25),
Score INT
); """
cursor_obj.execute(table)
print("Table is Ready")
# Close the connection
connection_obj.close()``` now?
HUH
?
did you change anything besides the table name?
... look at the email column ๐ญ
oh hell nah
????
i thought that was from geeks for geeks
they are weird sometimes
like maybe sqlite allowed that
CREATE TABLE IF NOT EXISTS warnings(
id INT NOT NULL AUTO_INCREMENT,
user_id BIGINT NOT NULL,
reason TINYTEXT
);
this should work for your Bot
the id is meant to be an unique UUID
nor count
to ensure uniqueness
hi
I guess that makes sense
in the table there could be multiple rows with the same user_id and the way to ensure uniqueness is to have a randomly generated id for every warning entry
this is an alternative than having an array in your table
which is not cool imo (having an array i mean)
having an array is cool but not possible in sqlite
and I don't think you need the radnom ID, it can just be incrementing
so in id u need to paste bot's id or user id?
yep just use AUTO_INCREMENT()
yeah true but a random id is cooler 
it's hard when ppl start with discord bots in their python journey
especially when they try things a little harder than what they can do
we're trying to make it simple here
no, the id can be auto-generated using your db built-in functions or a value that is incremented, as the others suggested
oh
if you want to use AUTO_INCREMENT as the others suggested you can use this schema, you will need to pass only the user_id and the reason
technically true, but as snowflakes store the timestamp in the most significant bits, you'll only reach sqlite's signed 64-bit int limit in 2084 (try discord.utils.snowflake_time(2**63-1))
(this is in fact also true for bigints in postgresql which are signed 64-bit ints like sqlite)
good to know, thanks :D
fyi the keyword is AUTOINCREMENT, but INTEGER PRIMARY KEY is usually sufficient unless you really need to prevent re-use of IDs after deletion
https://sqlite.org/autoinc.html
(ah just realized you were using mysql syntax)
ty
Hey i would like to ask for advice what to add to my discord bor, is this the place to do so? i am not quite sure ๐
just ask
py-cord is the best discord bot library of all time

ok
Not sure what that is ngl
ok
^anyone could give me an example
Ask someone in #media-processing
def getStockInfo(ticker_symbol, api):
url = f'https://api.twelvedata.com/quote?symbol={ticker_symbol}&apikey={api}'
response = requests.get(url).json()
name = response['name']
high = response['high']
low = response['low']
vol = response['volume']```
how can i grab each individual variable
like i want to get name, high, low, and vol
whoops wrong area sorry
thanks
Just return them?
i had to return them as a dict
yeah
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/7X3A
2024-02-29 01:28:30 WARNING discord.gateway Can't keep up, shard ID None websocket is 41.6s behind. why does this keep happening
u probably have some blocking code
where?
requests is blocking
is it?
u need to use aiohttp
ok
@bot.tree.command()
async def reactionroleadd(interaction: discord.Interaction, role: discord.Role, emoji: str , message_link: str):
embed = discord.Embed(title="Reaction Role created", description="Those who will react will get the role")
await interaction.response.send_message(embed=embed)
message = await interaction.channel.fetch_message(message_link)
if message.reaction.emoji == emoji:
await user.add_roles(role)
Upon using this command it gives a very long error
Send the error then
i need help,
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.```
Read the error
yeah i don't understand what's privileged intents
oh i found the setting my bad
wooho
how to update my bot after i add something inside?
re run the bot
yeah.. how to stop the bot then?
by closing the terminal that's running the bot...
well if ure using cogs u can reload it
im using vsc
!d discord.ext.commands.Bot.reload_extension
reload_extension(name, *, package=None)```
Atomically reloads an extension.
This replaces the extension with the same extension, only refreshed. This is equivalent to a [`unload_extension()`](https://docs.disnake.dev/en/latest/ext/commands/api/bots.html#disnake.ext.commands.Bot.unload_extension) followed by a [`load_extension()`](https://docs.disnake.dev/en/latest/ext/commands/api/bots.html#disnake.ext.commands.Bot.load_extension) except done in an atomic way. That is, if an operation fails mid-reload then the bot will roll-back to the prior working state.
I'm not talking about the editor

!d discord.ext.commands.Cog take a look
class discord.ext.commands.Cog(*args, **kwargs)```
The base class that all cogs must inherit from.
A cog is a collection of commands, listeners, and optional state to help group commands together. More information on them can be found on the [Cogs](https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html#ext-commands-cogs) page.
When inheriting from this class, the options shown in [`CogMeta`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CogMeta) are equally valid here.
i tried close and open the bot again then use py. main.py(its my file name), now it shows this py Traceback (most recent call last): File "D:\atest-bot\main.py", line 20, in <module> @client.command() ^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1520, in decorator result = command(name=name, cls=cls, *args, **kwargs)(func) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1793, in decorator return cls(func, name=name, **attrs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 406, in __init__ self.callback = func ^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 513, in callback self.params: Dict[str, Parameter] = get_signature_parameters(function, globalns) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 130, in get_signature_parameters raise TypeError(f'Command signature requires at least {required_params - 1} parameter(s)') TypeError: Command signature requires at least 0 parameter(s)
hmm
you'll also have to share the code
import discord
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print("Is logged in")
@client.command()
async def hello(ctx):
await ctx.send("Hello!")
@client.command()
async def ping():
await client.say('Pong')
client.run```
it works earlier, but not anymore
try giving the command a name in the decorator
which
well that's a misleading error
every command must have context as param, so do async def ping(ctx): instead
client.say doesnt exist anymore btw, use ctx.send
see example from the repo instead https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py
i will engrave this to my brain ๐ญ
much appreciated
Traceback (most recent call last):
File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\atest-bot\main.py", line 22, in ping
await ctx.send("Pong")
^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'send'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Kouma\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'send'```
???
code
error doesnt match code, did you save the file
but it able to use command "Shutdown" tho without saving
YAY IT WORKS
so i need to save every single time i added new code?
err, yes? if your IDE have an auto-save feature you dont have to
it should be
but it didn't
uh idk, maybe it only works when it changed
what IDE is this
what's IDE? the code editor? it's VSC
i see
vsc i think have a little bit of delay so you probably ran it before it auto save
pycharm autosave instantly
i've seen someone used pycharm and tbh it looks weird, as hell
sounds like human issue
is there anything i need to match to the current working commands?
those ppl send stuff like 2018 ish wth
hmm yeah i know it's reference but what does the (message) mean
I'm not sure what you're asking exactly
yeah i want if someone typed "Burn" the bot will automatically reply "Them"
most of the logic there is fine, only outdated one is send_message, it's channel.send instead
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File) objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list) of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed) objects. **Specifying both parameters will lead to an exception**.
@client.event
async def on_message(message):
if client.user.id != message.author.id:
if 'Burn' in message.content:
await client.channel_message(message.channel, 'Them')
await client.process_commands(message)```
oh wait
yeah
is it okay?
it won't trigger tho
it's just await message.channel.send('them')
the if?
nope
yes
thank you!!!
welcome
@golden portal do you know what should i fix?
there's no error code in the code viewer thing
What are you trying to do? What did you expect? What result did you get? What error do you get if any?
Either way you're probably better off making a command tho
i wan't to make when i @ping the bot it reply back with a message, thre are no error because it's not an error, just wrong code probably(and since it's not a triggered command)
omg help
my bot won't respond anymore
๐ญ
.
Is intents.message_content enabled?
Do you have another function with that name?
nice extension, but prob would make me not that productive xd
how did you make your environment so pretty? is that like a vscode theme? :0
sorry I know it's not related, just got curious lol
That would be a theme Iโm guessing yes ๐
Which one, Iโm not sure. ๐
https://paste.pythondiscord.com/KDAA can anyone fix?
i dont see that command in the code
its the same code but different name
you have to sync when you change names
I don't know, no clue. might need to import something in but I will do that after my school 
I've read this but I got no clue how to enable it
Has anybody else made Deal or No Deal game with their discord bot before? Actually does anybody like making games on discord bots? That my thing.
i had made
Um... okay.
A lot of people have likely made games, and im sure some have done deal or no deal before as well
I be very shocked if anybody done that. In fact, I'll be shocked if anybody even made a better version than the one I made. Well technically, I'm making a new improved version, but one thing trips me up.
I have never been able to figure out how they split their discord stuff into different files. Currently, every game and thing I have is on the same file.
Any one got a quick tip on how to sync my discord commands? Fiddling with discord again after a year or so, and I've somehow got duplicate commands. Tried limiting it to just guild, but no success. Any ideas?
the website are not valid anymore
oooraaah
Do you intend to have guild specific commands
Yeah just guild, not globals*
how are you syncing them?
@bot.event
async def on_ready():
await bot.tree.sync(guild=discord.Object(id=YOUR_GUILD_ID))```
That's what I found
I think you have synced to global before, they won't disappear after you synced to guild
That is most likely the issue now that you say it, makes sense. Now can I desync them from global?
How*
sync an empty tree to global, (so don't pass guild=) if all your commands are guild specific it should already be empty
How to make a argument optional in a slash command
don't you mean get_user?
@bot.event
async def on_ready():
await bot.tree.sync()```
Like so?
I assume I need to remove the commands that are syncing to the guild?
yuh uh
@supple locust is this how it is supposed to look?
are you not using client = commands.Bot() at like the top of your code? I thought you were
which means you should use client.get_user()
nuh uh, its bot = commands.Bot()
im already using client for something else
AttributeError: 'NoneType' object has no attribute 'create_dm'
heh, here we go again
This is why I said you probably want to make sure you check if anything is None along the way
typehint the argument with typing.Optional
create_dm is also none
the full thing would be typing.Optional[ScheduledEvent]?
i think
try what HyperCube is saying
ill try this
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
but remember to hide your token
ohhh
There shouldn't be both clients and bot in your code
how did you run the bot
client.run or bot.run
client.run
fuck, now you made sense
@north kiln Can't I just run both client.run and bot.run?
no
for the event problem, if you have a creator id dpy will attempt to set event.creator by creating a user from the id
so what you are facing is quite weird
maybe you should ask in dpy server
Yeah I did
I just dropped on them the paste link
hlo so i was gone for 3 years
what changes will i have to done to make my bot run again
eventUser = await bot.get_user(event.creator_id).create_dm(eventUser).send("Your event got cancelled.")
also this line is a problem, because you're trying to use eventUser in the create_dm() method before you've defined it, and that's also not how create_dm() is meant to be used, I'm positive it doesn't take any arguments. You're best to get rid of eventUser = and just use create_dm() not create_dm(eventUser)
import discord
from keep_alive import keep_alive
from discord.ext import commands
intents = discord.Intents.all()
activity=discord.Activity(name='Knife HQ pre alpha 0.0.1 \n prefix = pls', type=discord.ActivityType.watching)
bot=commands.Bot(command_prefix=["pls ","Pls ","PLS ","PLs ","PlS ","pLs ","pLS "],case_insensitive=True,activity=activity,intents=intents)
bot.load_extension('cogs.auto_task')
bot.load_extension('cogs.Battle')
keep_alive()```
discord.ext works still?
and cogs also
@supple locust same error
AttributeError: 'NoneType' object has no attribute 'create_dm'

