#General Help
1 messages Ā· Page 27 of 1
yeah, but i installed from shell, I don't like the replit package manager
Nevermind ima not use replit
oh
i cannot import commands.Bot
do you use this? https://namantech.me/pycord/installation/#replit
How to install the Py-cord library - Pycord Guide
𤦠I mean at bot = instead of discord.Bot
Use commands.Bot
well that was embarrassing
nw
from discord import Bot
ImportError: cannot import name 'Bot' from 'discord' (unknown location)
use "from discord.ext import commands"
^
Feel free to check my repo for my bot https://github.com/VividBlue1/Felbcord-Py if it helps you, Although dont copy code just learn from it and you can fix your issue
still same error
import discord.abc
ModuleNotFoundError: No module named 'discord.abc'
do you have something else installed?
You dont have import discord.abc in ur code
something from discord or discord.py?
Make sure discord py isnt installed as said above, pycord wont work with it.
these are the imports
import discord
from discord.ext import commands
from discord import bot
from lxml import html
import random
import requests```
and packages
Run pip list in your console and send the result
Try running this version instead
pip install py-cord==2.0.0rc1
this error
... clue in the name? 'improper token been passed,
If your using a env to store your token have it like this
bot.run(os.getenv("TOKEN"))
or without env
bot.run('TOKENGOESHERE')
well thats embarrassing again
What were you using before?
old token and wrong library i guess
Btw, You should use an env for your token its much safer for, github and if your sharing your code in this case. saves you delting the token
I was seeing guide for prefix through command.ext but the example code never reacted on using prefix commands
do you have message_content intent enabled?
?Tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
Thanks mate
For your valuable time and information
np, so it worked?
Let me check I've closed my laptop give me a second
Anyone able to help? I deleted my old repo and created a new one to try fix something (wasnt the issue anyways, lol) and i have this error after doing the instructions given after making the repo,
I deleted the old repo already so cant git pull
The "on_message" event does not detect messages from bots
are you sure it receives messages at all
yes
hi, when connecting to a channel how can i check if the bot actually joined the channel and it didn't fail due to permissions?
h
may be easier if you used github desktop.
if not ctx.interaction.guild.voice_client:
vc:wavelink.Player = await ctx.interaction.user.voice.channel.connect(cls = wavelink.Player, timeout = 10, reconnect = True)
await ctx.interaction.guild.change_voice_state(channel = ctx.interaction.user.voice.channel, self_deaf = True)
i am trying to add a check here, any ideas on it?
Ill try that, wouldnt i have the same error though?
doesn't ctx.guild.voice_client return None if it failed to join or something
it doesn't
send current on_message code
Hey, I want to make a /item use command for a bot with an inventory handler. I want the command to have an item option where the choices are only the items the user that started the command has in his inventory. Can somebody tell me how to do that ?
sounds like autocomplete would be helpful here
Here's the slash autocomplete example.
as said by squid, (but with addtion) install python extension if you use vsc and u can get auto complete
I think we are talking about different autocompletes
o lol
Yeah I already looked at that example, but I don't really understand how I can get the id of the invoker
I was talking about loading slash command options dynamically
Dont know about ID but for name u can use like {ctx.author.name}
Ah alr
I meant autocomplete for python lol
code ```py
@bot.event
async def on_message(message):
print(message)
Oh ok thx
and if you send messages it prints, but if it sends a message itself, it will not?
Is it just the bot itself or all bots?
The ac limits the user to the option(s) we give him right ?
All the bots
unfortunately, no
they can still type whatever they want and send it
but you can just check it
and throw an error back
Yeah I was hoping not to do that but ok then
how do you test that?
What now? I created the repo with the files you may see in the background
click fetch origin
and then click open visual studio code
and after you are done with vsc, go back to this page and click commit
after typing a summary
my bot responds twice to commands (slash commands are the only exception)
You must have 2 instances open
I have clicked open with vsc, but its a new bot file.. i want to make it on an existing folder
it's fine
code
just drag everything over
alr. will i need to re install stuff
am I supposed to send you the whole code?
regenerate token then do it @graceful robin
Is this to me?
When I tried the "say" command from another bot my bot didn't print the message
is it a slash command
no, to Czebosak#2281
No
Interesting. I get the messages fine from other bots when I do it. Are you sure it's not a permissions thing
probably not
huh? I have children added py File "/home/container/main.py", line 117, in bug modal = BugReport() File "/home/container/main.py", line 100, in __init__ self.add_item(discord.ui.InputText(label="Bug Description", required=True, placeholder="Explain the bug you've found...")) File "/home/container/.local/lib/python3.9/site-packages/discord/ui/modal.py", line 135, in add_item if len(self._children) > 5: AttributeError: 'BugReport' object has no attribute '_children' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/container/.local/lib/python3.9/site-packages/discord/bot.py", line 993, in invoke_application_command await ctx.command.invoke(ctx) File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 357, in invoke await injected(ctx) File "/home/container/.local/lib/python3.9/site-packages/discord/commands/core.py", line 134, in wrapped raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'BugReport' object has no attribute '_children'
Yes, I don't think it's a permission issue, since I gave the bot all perms
nothing changed
The .venv folder isnt correct, Its just the cfg file showing, whys that
Make sure you've updated the token too
the bot wouldnt start
what about restarting the computer so there might be loose things there.
?
then reinstall everything
alr
bruh the folders im moving wont go into my new folder for the repo its making new folders n stuff, Are you sure i cant use my current folder
this started like 2 weeks ago
I dont think that thats the problem
you can try
is it being hosted anywhere else
Can someone help me?
we need your code smh
ok smh
I think there is only me trying to help all of you
xD
I normaly help but im busy tryna sort this lol
if i see smth i can help with, i will
class BugReport(discord.ui.Modal):
def __init__(self):
self.response = None
self.add_item(discord.ui.InputText(label="Bug Description", required=True, placeholder="Explain the bug you've found..."))
# other items
async def callback(self, interaction: discord.Interaction):
bug_description = self.children[0].value
reproduction_steps = self.children[1].value
expected_results = self.children[2].value
actual_results = self.children[3].value
self.response = {'bug_description': bug_description, 'reproduction_steps': reproduction_steps, 'expected_results': expected_results, 'actual_results': actual_results}
self.stop()
return```
and its saying there are no items/children
no
try updating.
probably upload your code to pastebin or github gists
and then send that
ok can I upload a zip file? I dont have git setup
sure. if it doesn't surpass upload limit
and hide your token too
@slow dome ^
yes
I can't reproduce the issue with your code
Actually you are missing super().__init__()
weird.. my entire files in the commands folders and embeds ect ect, all deleted... luckily they were in my bin
... some gone
F my main file gone
:((
pog
how tf is that pog
you can rewrite it to be more efficient
True, but it was already fine
Ok i agree ima make this bot so much better
im happy
now i have other error: ```txt
Traceback (most recent call last):
File "main.py", line 62, in <module>
client = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
change the replit run part to "pip install py-cord==2.0.0rc1 && python main.py"
Hello, does anyone know why when using
if codeRegex.search(ctx.content):
does not detect the message sent to bot
its working, but any command works
slash commands doesnt work
normal commands either
just by isinstance(context, BridgeExtContext)?
Bruh, i am re writing my bot this ie the same as before and it works fine..??
import discord
from discord.ext.commands import slash_command
from discord.ext import commands
from discord.ext.commands import Cog``` why is discord.ext.commands could not be resolved
or when using discord.ext
cannot import name 'commands' from 'discord.ext' (unknown location)
@slow dome able to help? This works fine in my old code
Updated:
import discord
import os
from dotenv import load_dotenv
load_dotenv()
from discord.ext import commands``` (Just saw its in main file)
slash_command doesnt come from .ext.commands
it comes from discord.commands
Its worked fine in my other bot.? but ill fix that
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) @slender lintel
maybe try and reinstall pycord
alr
py-cord==2.0.0rc1
this is the correct version right
ye
why do you need ext.commands
I had discord.ext first, tried it after
thereās discord.Cogs and discord.slash_command
alr
is there a way to make the bot only do something on the first ready, bcz ive had instances of the bot randomly rebooting while running and that starts a 2nd loop on things like checking time for reminders
@client.event
async def on_ready():
# here
Hey since I updated pycord to newest version my bot throws a error and does not start anymore. I already asked for help this afternoon and someone said that I should add self as parameter . I did this my bot started again but then when i used a command another error came.
Error before I added self:
next(params)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground\main.py", line 2216, in <module>
playground()
File "c:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground\main.py", line 418, in __init__
async def help(ctx: discord.ApplicationContext):
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\bot.py", line 813, in decorator
result = command(**kwargs)(func)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 1580, in decorator
return cls(func, **attrs)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 644, in __init__
self.options: List[Option] = self._parse_options(params)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 676, in _parse_options
params = self._check_required_params(params)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 670, in _check_required_params
raise ClientException(f'Callback for {self.name} command is missing "{p}" parameter.')
discord.errors.ClientException: Callback for help command is missing "context" parameter.
PS C:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground>
After I added self parameter:
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 126, in wrapped
ret = await coro(arg)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 856, in _invoke
await self.callback(ctx, **kwargs)
TypeError: help() missing 1 required positional argument: 'ctx'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kingl\Desktop\Programmierung\Discord Bots\Slash Commands\playground\main.py", line 413, in on_application_command_error
raise error
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\bot.py", line 993, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 357, in invoke
await injected(ctx)
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 134, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: help() missing 1 required positional argument: 'ctx'
can you send the help() command definition?
@bot.slash_command(name="help", description="Sends the help menu")
async def help(self, ctx: discord.ApplicationContext):
is this in a cog?
does the class inherit from commands.Cog?
no
then why are you using self
because my bot does not start without self in every command
Why isnt
@slash_command(name='ban', description='Bans chosen member')
async def ban(
self,
ctx: discord.ApplicationContext,
user: discord.User,
reason: discord.Option(str, "Enter the reason")):
ban = discord.Embed(title=f'{user.name} was banned', description=f'{user.name} has been banned for {reason}', color=0x15B4E3)
ban.timestamp = datetime.datetime.now()
await user.ban()
await ctx.defer(f'**{ctx.bot.mention} is thinking**')
await ctx.respond(embed = ban)``` working, It returns user has no attrubite 'ban'
I had member.ban before but changed to user to try fix it
well
you type hinted it as discord.User
thats not the same as discord.Member
Yeah, discord.user is people in any server and discord.member has to be in the server
right
but whys it happening
@slash_command(name='ban', description='Bans chosen member')
async def ban(
self,
ctx: discord.ApplicationContext,
member: discord.Member,
reason: discord.Option(str, "Enter the reason")):
ban = discord.Embed(title=f'{member.name} was banned', description=f'{member.name} has been banned for {reason}', color=0x15B4E3)
ban.timestamp = datetime.datetime.now()
await member.ban()
await ctx.defer(f'**{ctx.bot.mention} is thinking**')
await ctx.respond(embed = ban)```
It dosent even respond
@slender lintel
something to do with your defer i believe
b!rtfm pyc defer
discord.DeletedReferencedMessage
discord.DeletedReferencedMessage.channel_id
discord.DeletedReferencedMessage.guild_id
discord.DeletedReferencedMessage.id
discord.Embed.footer
discord.Guild.preferred_locale
discord.MessageReference
discord.MessageReference.cached_message
discord.MessageReference.channel_id
discord.MessageReference.fail_if_not_exists
I tried await defer instead of await ctx.defer and it just says defer is not defined
no no
you have to do
await ctx.defer()
no input
ah alr
so remove f'{ctx.bot.mention} is thinking'
I was trying to make it say the bot is thinking then respond with the embed
Same error
i don't think there is a point in adding the defer
Is there a way to make sure when there's error for application commands, it focuses on the error that it's programmed to do. For example
this below v is for a command when activates a cooldown
async def on_application_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
Flight_Embed = discord.Embed(
title="Cooldown",
color=discord.Color.red()
)
Flight_Embed.add_field(
name="Command on cooldown",
value=f"\n> {error}"
)
await ctx.send(f" {ctx.author.mention}",embed=Flight_Embed)
and there's another application command which only certain roles can use it and if it detects user that doesn't have a role it sends in this
@bot.event
async def on_application_command_error(ctx, error):
if isinstance(error, commands.MissingRole):
Embed = discord.Embed(
title="Invalid User",
color=discord.Color.brand_red()
)
Embed.add_field(
name="User is not the chosen one",
value=f"\n> User is not permitted to run this command"
)
await ctx.respond(embed=Embed)
However for the cooldown error it sends the error message above ^ and I'm not sure how to separate it
because its just going to instantly send the message
How can i make it wait a few seconds
or like 5
So I'd put that right before my ctx respond
yeah
Alr thanks
Why would you asyncio sleep?
That's what I found out online to use
And what's the point of deferring and then instantly responding
thats what i said too lol
(oh mb you're talking to him)
@slender lintel You do
await ctx.defer() at the start of your response, do your actions and then respond.
No idea why you're deferring such thing when it just sends an embed
anyone got an idea for above ^^?
No, discord.user is just someone not attached to the server. discord.member is a discord.user + the guild it's attached to
I want to send a normal message first then a few seconds later a embed
That's what I meant
and discord.User actually doesn't have anything to do with ban
I love it when my thoughts go faster than I can type
relatable
like, maybe I should type it this way instead and it turns out I just mess up even more
So howd I do this without sleep
so why would you want to do that
Cause I want to have it like
Felbot is thinking
3 seconds later
Embed response
Making the bot slow on purpose is not a good idea
Rip alr
its not because it effects the bot or anything but as squid said it would waste the persons time if they used the command.
having it send immediately would be more beneficial and convient
Tru
I didn't say that, but ok
oh mb.
It's literally unnecessary coding
i read it then did something and came back and your words just reworded itself in my brain
not that I disagree, but yeah
I wanted it like this
why do you want it to think
But that's actually because the bot needs to process a bunch of code
oh I think you just want it to say something when it is processing it
but not actually increase run time
@slash_command(name='ban', description='Bans chosen member')
async def ban(
self,
ctx: discord.ApplicationContext,
member: discord.Member,
reason: discord.Option(str, "Enter the reason")):
await ctx.defer()
ban = discord.Embed(title=f'{member.name} was banned', description=f'{member.name} has been banned for {reason}', color=0x15B4E3)
ban.timestamp = datetime.datetime.now()
await member.ban()
await ctx.respond(embed = ban)
just put the defer at the beginning
For the appliaction error event, is only one of the event required?
what does that mean
so I have one command that initiates the application error when on cooldown
and another if a user doesn't have the required role
lemme scroll up to find my message
here ^^
Check instances?
wait i forgot to update it
yeah, you should only have one
if a specific command differs from the rest of the commands, you can handle that one with
@command_name.error
would i put it under the command? or along with the event handler?
look, on_app_cmd_err handles all errors
while @command_name.error only handles the same one
if you are going to have different error messages then @command_name.error
otherwise, it would be better for on_app_cmd_error
I used on_app_cmd_error but I needed different messages for those 2 cooldown commands
one is in 10 secs another in 30 mins and if I use maths to convert secs into mins
both of them can converted
hi guys
i am new to pycord
how to do a thing like this
it updates the discord user count and the online member count on the server banner
does anyone have some SQL knowledge?
use PIL to create the banner, then update the guild banner
tbh don't do that. That easily throws you into ratelimits.
if not ctx.interaction.guild.voice_client:
vc:wavelink.Player = await ctx.interaction.user.voice.channel.connect(cls = wavelink.Player, timeout = 10, reconnect = True)
await ctx.interaction.guild.change_voice_state(channel = ctx.interaction.user.voice.channel, self_deaf = True)
So if the bot does not have enough perms , how can i add a check in this piece of code that the bot actually is joining the channel
and for some reasons, is_playing does not return None
rather, nothing is returned none
i am stuck here for 2 days, pls help me
basically, i just want to know which thing is returned as none if the bot can not join a vc due to permission error
maybe create a seperate help thread for that. could become complicated 
if i had a very long string s, how would i send it as a file
wait i think ik how to do it imma try it rq
nvmd my solution ended up very hacky of turning a stringio into a bytesio
ctx.respond returns the message than you can edit it with message.edit()
does anybody have a better solution than this
uteError: 'Interaction' object has no attribute 'edit'\
i have message = ctx.respond()
and then message.edit
Opp I told you wrong. You need to use edit_original_message for editing Interactions.
for color in ROLES.colors:
for i in range(len(ROLES.colors[color])):
print(int(list(ROLES.colors[color][i].keys())[0], 16))
role = discord.utils.get(
ctx.guild.roles, name=ROLES.names[color], color=int(list(ROLES.colors[color][i].keys())[0], 16))
print(role)
if not role:
await ctx.guild.create_role(name=ROLES.names[color], color=int(list(ROLES.colors[color][i].keys())[0], 16))
else:
pass
for i, number in enumerate(ROLES.numbers):
emote = discord.utils.get(
ctx.guild.emojis, name=ROLES.numbers_names[i])
if not emote:
with open(number, errors="ignore") as f:
image = f.read()
await ctx.guild.create_custom_emoji(
name=ROLES.numbers_names[i], image=image)
else:
pass
for reference
colors = {
"white": [{"0xFFFFFF": "role"}, {"0xF5F5F5": "role"}, {"0xF0FFF0": "role"}, {"0xF0FFFF": "role"}, {"0xF8F8FF": "role"}, {"0xFFF5EE": "role"}, {"0xFFFAFA": "role"}],
"black": [{"0x000000": "role"}, {"0x111111": "role"}, {"0x222222": "role"}, {"0x333333": "role"}, {"0x444444": "role"}, {"0x555555": "role"}, {"0x666666": "role"}, {"0x777777": "role"}, {"0x888888": "role"}],
"red": [{"0xFF0000": "role"}, {"0xFFA500": "role"}, {"0xFF4500": "role"}, {"0xFF6347": "role"}, {"0xFF7F50": "role"}, {"0xFF8C00": "role"}, {"0xFFA07A": "role"}, {"0xFFB6C1": "role"}, {"0xFF0000": "role"}],
"orange": [{"0xFFA500": "role"}, {"0xFF8C00": "role"}, {"0xFF7F50": "role"}, {"0xFF6347": "role"}, {"0xFF4500": "role"}, {"0xFFA07A": "role"}, {"0xFFB6C1": "role"}, {"0xFFA500": "role"}, {"0xFF8C00": "role"}],```
"yellow": [{"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}, {"0xFFFF7F": "role"}, {"0xFFFF00": "role"}],
"green": [{"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}, {"0x00FF7F": "role"}, {"0x00FF00": "role"}],
"blue": [{"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}, {"0x0000FF": "role"}],
"purple": [{"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}, {"0x800080": "role"}],
}
names = {
"white": "ć",
"black": "ć",
"red": "ć¬",
"orange": "ćŖ",
"yellow": "ć¤",
"green": "ć°",
"blue": "ć",
"purple": "ć",
}
numbers_names = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
]
numbers = [
"./core/assets/emoji/1.png",
"./core/assets/emoji/2.png",
"./core/assets/emoji/3.png",
"./core/assets/emoji/4.png",
"./core/assets/emoji/5.png",
"./core/assets/emoji/6.png",
"./core/assets/emoji/7.png",
"./core/assets/emoji/8.png",
]
Traceback (most recent call last):
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "D:\Documents\Coding\Discord\Eclipse\utils\cogs\colorRoles.py", line 24, in colorroles
await self.init(ctx)
File "D:\Documents\Coding\Discord\Eclipse\utils\cogs\colorRoles.py", line 60, in init```
await ctx.guild.create_custom_emoji(
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\guild.py", line 2597, in create_custom_emoji
img = utils._bytes_to_base64_data(image)
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\utils.py", line 523, in _bytes_to_base64_data
mime = _get_mime_type_for_image(data)
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\utils.py", line 509, in _get_mime_type_for_image
if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
TypeError: startswith first arg must be str or a tuple of str, not bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "D:\Documents\Coding\Discord\Eclipse\venv\lib\site-packages\discord\ext\commands\core.py", line 190, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes
im assuming the error is because the image im passing into the create_custom_emoji function is a byte array and it's asking for a string though the documentation says it's supposed to take in bytes?
im a little confused
Does on_error get every discord.DiscordException error?
Does anyone know why this doesn't work? The command only works when I have a small number as the timeout but not 3600 (An hour)
await bot.wait_for("message", timeout=3600)
...
can i have a 2x2 of embed fields?
this is about the best you can do as far as im concerned:
embed = discord.Embed(
fields=[
discord.EmbedField(name="a", value="b", inline=True),
discord.EmbedField(name="c", value="d", inline=True),
discord.EmbedField(name="\u200b", value="\u200b", inline=False), # \u200b should create an empty space character
discord.EmbedField(name="e", value="f", inline=True),
discord.EmbedField(name="g", value="h", inline=True),
]
)
you can also just change it to be dashes or something kinda like a border
Wouldn't it be embed.addfield
Alr, so it won't make it break the way I said
nope
Alr
to spare you the testing:
Thanks! I had an issue with it not being 2x2 but just ignored it but now I can fix it
I have a question, is it posible, that custom emojis work in embeds responding to an interaction?
I've noticed that jump_url has been added to User class recently, 6/25 to be specific.
is there a way to use the jump_url in the newest version, i.e. 2.0.0rc1?
I've tried and got error saying that the attribute dose not exist.
yes
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'jump_url'
and this is the error msg i got
em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Boosters")
em.add_field(name=f"A list of every person that has boosted **{ctx.guild}**",value=f"{booster.mention}")for booster in ctx.guild.premium_subscribers:
em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Boosters")
em.add_field(name=f"A list of every person that has boosted **{ctx.guild}**",value=f"{booster.mention}")``` how do i make it so that the boosters are sorted with numbers
You mean
1: User1
2: User2
3: User3
Or
User1: 1 Boost
User2: 2 Boosts
the first one
x = 1
for booster in ctx.guild.premium_subscribers:
em = discord.Embed(color=discord.Color.from_rgb(13, 99, 143),title="Boosters")
em.add_field(name=f"A list of every person that has boosted **{ctx.guild}**",value=f"{x}: {booster.mention}")
x += 1
ty
a better way to do this is to use enumerate() to also get the index
also how do i get the boost count of a specific booster
Idk if its possible
oh alright
NotFound: 404 Not Found (error code: 10062): Unknown interaction
the command works but its not able to respond to the "Message"
... Code
i deleted it cuz i fixed it mb
@commands.command(name="purge")
async def purge(self, ctx, limit=5):
await ctx.channel.purge(limit=limit)
error:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'PartialMessageable' object has no attribute 'purge'
intents
intents = discord.Intents()
intents.message_content = True
intents.messages = True
intents.members = True
(in cogs)
v2.0.0b7
i cant use normal commands,only slash commands work idk why
you might be missing message content intents
?tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
What about your on_message event?
it has an await bot.process_command(message) right?
what is your current code
its 500 lines but slash commands work, the one with the normal command is this: @bot.command()
async def test(ctx):
print("yh")
ik it doesnt need ctx but i jst changed it to printt sumthing to look if it wld work
but nope
are you using discord.Bot or discord.ext.commands.Bot
discord.Bot
it doesn't support old styled commands
oh
bot.command in this case will make slash command
oh ty
try changing to ext.commands.Bot and using bot.command for default commands and bot.slash_command for slash
commands.Bot will create prefixed commands
so i just replace discord.Bot with discord.ext.commands.Bot with
alright ty
Are those commands going to have the same functionality or different?
slash commands and prefixed?
same
you can use bridge commands for that
then, using discord.ext.Bridge.bot would be better
Bridge creates slash and prefixed with a single function
but there is some breaking changes in behaviour (at least when i used it there was)
so check the docs
and the guide
module 'discord.ext' has no attribute 'bridge'
Concept
imma see
you should update probably
yup works now tysm
šš»
I'm not sure if you're able to delete Link Buttons
but this is my code, and it doesn't work, is it possible to remove link buttons?
describe "doesn't work"
as it removing the link button
Sanity check - can Role Images be displayed for inline use, maybe using emoji tags or something similar?
self is the view, correct?
Unless you upload it as an emoji
nvm
yes, you can
I see the icon asset, but wasn't sure if that could be printed alongside the role, since I would've assumed an asset would act as an attached file
Will play around with it, just wanted to see if it was worth spending the time. Thanks
no, there is Role.unicode_emoji
where it is a string
Yeah but if you use a registered but custom emoji, it's then not unicode
you can try, ig
yepyep.
how did you add the url button
class Flight_Button(View):
def __init__(self,bot):
super().__init__(timeout=None)
self.bot = bot
Private_Button = Button(
label= "Private Server",
style= discord.ButtonStyle.url,
emoji=":link:",
url= "ee"
)
self.add_item(Private_Button)
@discord.ui.button(
label="Flight Reviews",
style=discord.ButtonStyle.green,
emoji=":star:"
)
async def callback(self,button,interaction):
Server = self.bot.get_guild(ee)
User_ID = interaction.user
Role_Review = Server.get_role(ee) # Needs to change this to Flight Reviewer
await interaction.response.send_message(f"You have been given the {Role_Review.mention}",ephemeral=True)
await User_ID.add_roles(Role_Review)
@discord.ui.button(
label="Flight Departed",
style=discord.ButtonStyle.green
)
async def green_button_callback(self,button,interaction):
if interaction.user.id == 481099018676600853:
Private_Button = Button(
label= "Private Server",
style= discord.ButtonStyle.url,
emoji=":link:",
url= "EEE"
)
self.remove_item(Private_Button)
for child in self.children:
if child.label == "Flight Departed":
child.style=discord.ButtonStyle.red
child.disabled = True
await interaction.response.edit_message(view=self)
else: await interaction.response.send_message("Egg",view=self,ephemeral=True)
the whole code
It should work, I guess that removing link buttons aren't supported. In alternative, you can create a new view and use that instead...
I wanted to remove the link button as I want few buttons to stay as well
what about clear_items() will that help?
yeah, just save the self.children before and then re-add them after
why html
Or .txt
you can fetch the channel history
with await channel.history(limit=xxx)
b!rtfm channel.history
I couldn't find a documentation with the name channel.history! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake
b!rtfm pyc channel.history
he conflict is caused by:
The user requested py-cord==2.0.0rc1
py-cord[speed] 1.7.3 depends on py-cord 1.7.3 (from https://files.pythonhosted.org/packages/04/16/808ad971642cdd66e719edb6107a0e065608dd383f05a9389a34dddf7bb4/py_cord-1.7.3-py3-none-any.whl#sha256=19cb49ee6cb830d71e8b5d9555249cef5c15c652c096176e69edce5ff993701b (from https://pypi.org/simple/py-cord/) (requires-python:>=3.5.3))
To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip attempt to solve the dependency conflict
ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts
! Push rejected, failed to compile Python app.
! Push failed
is there pycord[speed] on 2.0.0rc1?
yes
how then to install it?
py-cord[speed] == 2.0.0rc1
!tag install
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord beta:
pip uninstall discord.py
pip install py-cord==2.0.0b7
Install pycord alpha from git:
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
import discord
from discord.ext import commands
bot = commands.Bot(commands_prefix="f!")
@bot.event
async def on_ready():
print(f"{bot.user} is ready!")
@bot.command()
async def hello(ctx):
print("hi")
await ctx.reply("Hello World!")
bot.run("")
I run this code and gives me the confirmation that its running
but the command doesn't give me an output
I've checked permissions and the bot has admin
?tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
How to save it in a file?
you create a file and write to it
in what version is timeout inplimented?
timeout for what
users
because im getting a
Command raised an exception: AttributeError: 'Member' object has no attribute 'timeout_for'
error
just upgrade to rc1 and you're on the latest version
How to do it automatically
if i upgrade for some reason my bot ignores me lmfao
message content intent?
it has that
im assuming its because of the code i use for diffrent guilds have diffrent prefixes
I added message content intent but i now get a runtime error
earliest version is b5, i think
how do i check version again?
ok are you going to tell us what runtime error it is?
pip list
RuntimeError: Event loop is closed
traceback
oh i have py-cord 1.7.3
that's just discord.py
File "c:\Users\tanay\Documents\All_Python_Projects\Food Bot\test.py", line 13, in <module>
bot.run("")
File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 715, in run
return future.result()
File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 694, in runner
await self.start(*args, **kwargs)
File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 658, in start
await self.connect(reconnect=reconnect)
File "C:\Users\tanay\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 599, in connect
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.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022E27E36320>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022E27E36320>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 750, in call_soon
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1520.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed```
You havent enabled intents in the developer portal
this is what i mean
anyone know how to make a button for each result in a database?
I've enabled it here
If this isn't the right place, Idk where
pip install py-cord==2.0.0b5
Do you want specifically beta 5 or the latest beta?
What intents are you requesting anyways
intents = discord.Intents()
intents.message_content = True```
ok, you also need the messages intent to receive on_message calls.
Ohhhh ty
Hey, I have tried making a reason option unrequired because its a ban command, but it just adds an arg
import discord
from discord.commands import slash_command
from discord.ext import commands
import datetime
from discord.commands import Option
class Ban(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(name='ban', description='Bans chosen member')
async def ban(
self,
ctx: discord.ApplicationContext,
member: discord.Member,
reason: Option(str, "Enter the reason"), required=False):
await ctx.defer()
ban = discord.Embed(title=f'{member.name} was banned', description=f'{member.name} has been banned for {reason}', color=0x15B4E3)
ban.timestamp = datetime.datetime.now()
await member.ban()
await ctx.respond(embed = ban)
def setup(bot):
bot.add_cog(Ban(bot))```
How can i get text from embed fields?
How do you get a bot to join the same vc as the user?
required=False is outside of the brackets
put it inside Option()
Oh yeah, thanks.
Btw if you dont mind me asking, How would i also have a tempban command? So i can use member.ban fine but howd i have it use a time?
wdym?
like ban someone then unban them later?
Yeah basicly
after a certian amount of time
One way is using asyncio.sleep()
but that way is bad
so you should store the time the person should be unbanned in a database
then unban when it is time
I know how i can store my data, but im not sure how id specify any time?
get the current time and add on the time
I now get 'Not a vaild value'
then store that time in the database
thanks
did you add a comma?
reason: Option(str, "Enter the reason",required=False)):```
My description for the embed uses {reason}, Could that be why
I don't think that should be a problem
Hmm, what could be causing it then?
@slash_command(name='ban', description='Bans chosen member')
async def ban(
self, ctx: discord.ApplicationContext,
member: discord.Member,
reason: Option(
str, "Enter the reason",
required=False
) = "No reason provided."
):
await ctx.defer()
ban = discord.Embed(
title=f'{member.name} was banned',
description=f'{member.name} has been banned for {reason}',
color=0x15B4E3
)
ban.timestamp = datetime.datetime.now()
await member.ban()
await ctx.respond(embed = ban)
try this real quick
I gave reason a default value
Thanks, It works now
Since you wouldnt have a value when you dont give it one, reason will be None
Yeah, Ic now
@slash_command(name='unban', description='Unbans chosen member')
async def ban(
self,
ctx: discord.ApplicationContext,
user: discord.User,
reason: Option(
str, "Enter the reason",
required=False
) = "No Reason Given."):
await ctx.defer()
unban = discord.Embed(title=f'{user.name} was unbanned', description=f'{user.name} has been unbanned for {reason}', color=0x15B4E3)
ban.timestamp = datetime.datetime.now()
await user.unban()
await ctx.respond(embed = unban)``` If i use this for my unban command, Does it allow User ID (as you obviously cant mention them)
probably
ill try it ig
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'User' object has no attribute 'unban'
Nope, What can i use instead of user.unban?
prob just do member
ill try that
ctx.guild.unban(user, reason)
await ctx.guild.unban(user,reason)
Expected 2 args but 3 were given, i assume its thinking the comma was a arg? or howd i fix this
nah commas cant be an argument
Whats causing it then?
ctx.guild.unban(user, reason=reason)
ah alr
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10026): Unknown Ban
it means they arent banned
bruh they are..? Its my alt
hmm
correct id?
Yes, Ill double check tho
Weird
b!rtfm pyc unban
how do you get the voice channel a user is connected to
ok turns out it was an error with intents
await ctx.respond(f'Rickrolled {member.name}', ephemeral=True)``` Bruv why isnt it ephemeral
for result in results:
collectionafk.delete_one(result)
await message.channel.send(f"You have been removed from AFK {message.author.mention}")
if message.mentions:
results = collection.find({"member": message.author.id})
for result in results:
collection.delete_one(result)
if message.content == result:
await message.channel.send(f"This person is currently AFK" ``` how do i check if the mentione user is inside the collection? the code above spams messages
no wonder it spams messages its in a for loop lol
member.voice.channel
line 494, in on_message
if message.author.id in results:
RuntimeError: await wasn't used with future
for mention in message.mentions:
if mention.id in results:
await message.channel.send("he afk")
if message.author.id in results:
await collectionafk.delete_one(results)
```thought this might work to remove tthe afk
??
did you defer?
yea
well
the defer needs to be ephemeral
alr
await ctx.defer(ephemeral=True)```
ty
?
is there a way to ban someone from a certain server with guild ids
to ban someone from a list of guilds, you will just need to fetch the guild and fetch the user object and use guild.ban(user)
how do i fetch the guild i did everything but i didnāt know that part
b!rtfm pyc bot.fetch_guild
bet thanks
gl
Since when can you add custom message to defer by the way?
i didnt know that
since Discord listened to their own customers (which is never)
fyi proper usage of defer is to use it at the very first line of the command
we solved that yesterday
Is it possible to have cogs auto reload when edits are made?
you can reload the bot with something...
I already try to find
do you have nodejs installed?
No, I don't
Oh
Possibly dumb question but can you add bridge commands to subcommand groups?
Easy workaround if not but it'd make it neat
is it possible to receive voice audio as a stream with pycord? i know you can use start_recording() + stop_recording(), but this doesn't provide an audio stream to use
How do I make the buttons work even after restarting the bot?
Here's the persistent example.
@rigid wave
and how in cogs?
The same way?
how to get a role from its initial 2 or 3 letters?
like we get in dyno or probot where ?role <user> mod and it will add moderator role
Try typing the argument to discord.Role this might convert it to the closest name.
Is there a way to set a home guild for a bot
So that guild is always cached on start
fetching it will cache it
can you fetch it before the on_ready() call?
Iām assuming that will mess up the cache
maybe yeah
I jus thought since chunking exists, if you could only chunk one guild lol
also, does fetching the guild cache all the channels too
what's the difference between self.bot.fetch_channel() and Guild.fetch_channel()
how does the self.bot know what guild to fetch from
bump
OH YES
Depends on the context
Hello so i wanna add new button so like a row.
in here in the view do i just put a ","
so like view=view1, view2
like that?
How can i make select menu work 1 time?
A message can only have 1 view.
You add them to a view
buttonfish.callback = button_callback
view1 = View()
view1.add_item(buttonfish, buttonhunt, buttonfarm)```so in here like this??
like that i just add ","?
@sudden path
kk
Disable it on the callback
Is pycord filtering xss injections?
discord should filter that lol
A Moderator wrote this on discord developer discord
yeah so you have your answer, its up to you
we aren't responsible for filtering this lib side, because discord doesn't send xss stuff to bots
if you have a bot panel or something, that's your work, not our
Yes thanks
That was the thing i wanted to know
ok perfect š
does anyone have a solution to accessing the cog inside an autocomplete option
Is there anyway I can use "bot" inside of a discord.ui.button?
its better to use the callback and handle it in the function which created the button rather than running stuff inside the button itself
Could you link me the callback please
Sorry I am just new to this library that's all
its in one of the examples on the github, lemme check
hwy
hey
after using await interaction.response.edit_message
how can i edit the message after that
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/confirm.py at master Ā· Pycord-Development/pycord
inside the confirm view class theres 2 buttons with the callback function which set self.value to a value for the ask function to look at
thanks
I just want to be able to request info from a DB inside of the button
When someone presses it
?
just pass bot through in the arguments of the view and set it as self.db or something so it can be accessed in the buttons own function
noteason i think when you do send_message or whichever function you used to send the message it returns the message object so you could just keep that message object to run message.edit
message.edit doesnt work for interactions
Hmm alright ill try it rq
oh are you trying to edit the view?
no
basically
i will run a slash command, then it will show an embed with a dropdown view, after i click something on the dropdown view it edits the message once with interaction.response.edit_message, but then im wondering how to edit the message after that
Another question
So i dont have to filter any message from a user
discord.errors.ExtensionFailed: Extension 'cogs.suggest' raised an error: TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I defined bot in my class
class SuggestionButtons(discord.ui.View, bot):```
and imported bot from main import bot
i have it usually set to self.bot.db
Would it be smart to use nodemon to reload cogs? Its slash commands though...
self.bot.unload_extension(f'cogs.{extension}')
self.bot.load_extension(f'cogs.{extension}')```
I just do that
Works fine for me
Yeah but your not supposed to do that for slash commands
?
can you guys recommend a good async sql libary to use with python pls
aiomysql
^
Is it possible for me to use the variable "bot" defined in main.py in my discord.ui.View?
pass the bot instance when instantiating an instance of your class
ty
class SuggestionButtons(discord.ui.View, bot):
I've got that ATM
And it returns this error
you need to make an __init__ method
yes but remove the bot from the class args
probably not, as long as you don't build something with on_message as commands
its not valid
what now?
now you set any attribute of the instance (bot is most common) to the passed object
class SuggestionButtons(discord.ui.View, bot):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Upvote", emoji="ā¬", style=discord.ButtonStyle.green, custom_id="persistent_view:upvote")
async def upvote(self, button: discord.ui.Button, interaction: discord.Interaction):
msg = await self.bot.db.select("suggestions", ["*"], checks=[["status", 0]], single=True)```
This is what I have I have bot.db defined in main.py
yep
oh
and remove bot from the parenthesis for the class
Yeah i did
Now it's not working
No error or anything
It's not sending the original embed with the buttons
show related code?
class Suggest(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
@commands.cooldown(1, 30, commands.BucketType.user)
async def suggest(self, ctx, *, suggestion):
embed = discord.Embed(title=f"Exod | Suggestions",
description=f"""
ā **Suggestion**
`{suggestion}`
ā **Information**
`-` **From:** {ctx.author.mention}
`-` **Status:** :orange_circle:
`-` **Upvotes:** 0
`-` **Downvotes:** 0
""", colour=col)
embed.set_image(
url="dsds")
channel = self.bot.get_channel(970645293886500914)
msg = await channel.send(embed=embed, view=SuggestionButtons())
await self.bot.db.insert("suggestions",
[["message_id", msg.id], ["user_id", ctx.author.id], ["suggestion", suggestion]])```
oh btw if youre gonna have multiple instances of that view, youre gonna run into trouble with custom id conflicts
Yeah i was gonna remove the custom_id anyway
nothing seems to be wrong
Is it because it's in the same file as the COG?
like
I have 2 classes in the cog
commands.Cog
it shouldnt matter
?
oh i can see that youre not passing the bot when youre instantiating the view object
wdym
3rd to last line
self.bot since its in a cog
Anyone?
How do I remove/add a specific button using custom_id?
Can I edit a already sent message via ID?
yes
m.edit should work
AttributeError: 'int' object has no attribute 'edit'
Is it because I've set msg to the ID?
Nevermind dw
?
?
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
TypeError: upvote() missing 1 required positional argument: 'interaction'
Not seen this error yet...
code bruh
@discord.ui.button(label="Upvote", emoji="ā¬", style=discord.ButtonStyle.green)
async def upvote(self, ctx, button: discord.ui.Button, interaction: discord.Interaction):
#Embed stuff here
m = ctx.fetch_message(msg[0])
m.edit(embed=embed)
await interaction.response.send_message("Upvote", ephemeral=True)```
hmm
have local error handlers for bridge commands been added?
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/ui/view.py", line 371, in _scheduled_task
await item.callback(interaction)
TypeError: upvote() missing 1 required positional argument: 'interaction'
Does anyone know how to fix this error?
interaction.edit_original_message
#help-rules
š
which version is it on?
master branch
so i dont have to update my pycord library? that doesnt seem right
you still need to, because you are on an old master branch
in other words, do i have to pip install anything to access this feature?
yeah
what would the command be?
?tag install
-
Uninstall
discord.pyor any other forks of discord.py you might have with the namespacediscord.
python -m pip uninstall discord.py discord -y -
Install
py-cord
python -m pip install py-cord
Installing other builds:
Note: You need to have git installed. Use !git to find out how to install git.
Updating the module to Alpha (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
Updating to release candidate:
pip install py-cord==2.0.0rc1
the alpha one
thanks
Anyone know wtf this suddenly is?
I don't even need or use the voiceclient stuff
it happens on literal bot startup.
Have you installed pycord?
can you send your pip list output?
anybody know how to make pagination make a new page if the page before fields get full?
many people canāt find the error to this code, does anyone know?
Code:
@bot.event
async def on_guild_join(guild):
server = await bot.fetch_guild(guild.id)
print(server.channels)
hi = await server.channels[0].create_invite()
channel = bot.get_channel(988031087424983090)
stuff = guild.owner
jem = discord.Embed(color=0x2f3136)
jem.set_author(f"{bot.user} has joined a new server:",icon_url=bot.avatar.url)
jem.set_description(f"Server owner ID: {guild.owner_id}\
Server owner tag: {stuff.tag}\
Server name: {guild.name}\
Server ID: {guild.id}\
Server member count: {guild.member_count}\
Server invite: {hi}")
await channel.send(embed=jem)
Error (full trace back):
Ignoring exception in on_guild_join
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/container/main.py", line 37, in on_guild_join
hi = await server.channels[0].create_invite()
IndexError: list index out of range
^ I have all intents enabled
what if the server has no channels
i invited it to my second "test server" which has plenty of channels, yet I still get this error
š¤
Is it possible to get the message to which a thread is "attached" to without parsing it from the jump_url?
access attribute thread
actually no
access attribute channel and check if its a Thread
?
isinstance(msg.channel, discord.Thread)
I know that it is a thread. I want to know the "normal" message to which the thread is attached
as in that the first message derives from a message that was sent to a text channel?
actually that was just merged into the master branch
example:
on_thread_update I get the thread and I want to know to which text channel message the thread belongs
nice :D
Thread has the starting_message attribute that has a Message present if the first message was sent to a text channel from which the thread was created from
i reckon you could access the channel attribute of that
just that it can be None if not in the cache, which happens quiet often in bigger bots 
will check!
since the ID of the message is the same as the thread ID you can probably try and fetch the message if Thread.starting_message returns None
The ID for this message is the same as the thread ID.
you could use this to your knowledge
omg you are right! Didn't recognise that š
thanks guys :D
that even saves me a database field :P
nice
b!rtfm pyc embed.set_image
Not a valid image link, it seems like
shouldn't that read "guild.channels" and not "server.channels" ?
i had to post the img again
they fetched the guild and stored it into a variable called server
just saw that.
interesting. I'd personally do a console output as to what the list is, so you can see what data it's trying to work with.
under where I store server as a variable, I do have print(server.channels), lol
I think it's a caching issue.
any way I could resolve that?
that is only able to work once
after u do that once u cant again
I have no problem using it
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send('This command is on cooldown, you can use it in {round(error.retry_after, 2)}')
it doesnt handle it
itt jst gives the error in terminal
wait you can add cooldowns that easily?
slash commands use a different error handler
b!rtfm pyc on_application_command_error
oh my ty, i was about to make my own cooldown using json and stuff š
how do i use buckettypes?
but idk how to use them
for a cooldown
@commands.cooldown(2,5,"user")
is what i tried
bucket type is how you want to enforce the cooldown
how would i define one tho?
im bad at explaining
commands.BucketType.user for your example is how you want to use it
oh thanks
Is there a way to add checks for cog listeners like in commands?
how do i get the bots avatar url?
bot.user.(display_)avatar.url
display?
text inside the brackets is optional but heavily encouraged as it will always result in an Asset object
how do you check a cog listener
like it wouldn't listen if the event came from a certain server
Iām trying to use it in the author section of my embed, so like this?:
embed.set_author("test stuff,icon_url=bot.user.display_avatar.url)
yes
got it, ty
you can still filter it with
if not (something):
return
yep i've been doing that, i was just wondering if there was another way to do so
what does this even mean š¤
Could be wrong, but author field is for text. Youāre looking for url.
i have icon_url=xxx?
it can aha
I thought that was a diff field. Could be wrong though. Iām gonna look it up
one sec Iāll get a ss
It only takes keyword arguments
You haven't provided name=
b!rtfm pyc embed.set_author
i need to do that??
strange
Iād assume thatās only when Iām providing an icon?
it doesnāt get less confusing
ermm
slightly confused?
some you need to set, some are just assigned
b!rtfm pyc embed.descrip
Iām using jem.set_description
and jem is my embed definition
so Iām confused?
help
cant install pycord
just downloaded python 3.10
but i still cant install pycord
Can't read your mind mate. Provided errors / explain what's happening
PS C:\Users\proje\OneDrive\Documentos\code> pip install py-cord==2.0.0rc1
pip : O termo 'pip' não é reconhecido como nome de cmdlet, função, arquivo de script ou programa operÔvel. Verifique a grafia do nome ou, se um
caminho tiver sido incluĆdo, veja se o caminho estĆ” correto e tente novamente.
No linha:1 caractere:1
+ pip install py-cord==2.0.0rc1
+ ~~~
+ CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
this is what it says
every single pip command dont work btw
help plase
try py -m pip
well did it work?
yes
then use it instead of pip
you may have botched something during the install process but the alternative is the exact same so it doesnt matter
i have stuff = guild.owner then {stuff.tag} but I get this error: AttributeError: 'Member' object has no attribute 'tag'
b!rtfm pyc Member.tag
is it possible to get with on_voice_state_update: Member server muted/deafed, member was MOVED into a channel?
b!rtfm pyc member.mention
\n 
ty
Iāve been doing n\ š„“
oh god
now a EOL while scanning string literal err
think I fixed it
help?
code
async def _8ball(self, question):
embed = discord.Embed(title = question, description = random.choice(ball_responses))
await ctx.respond(embed=embed)
ball_responses = [
"Es cierto.",
"Es decididamente asĆ.",
"Sin duda.",
"SĆ definitivamente.",
"Puedes confiar en ello.",
"Como yo lo veo, sĆ.",
"M Ɣs probable.",
"Perspectivas buena.",
"SĆ.",
"Las seƱales apuntan a que sĆ.",
"Respuesta confusa, intenta otra vez.",
"Pregunta de nuevo mƔs tarde.",
"Mejor no decirte ahora.",
"No se puede predecir ahora.",
"ConcƩntrate y pregunta otra vez.",
"No cuentes con eso",
"Mi respuesta es no.",
"Mis huevos dicen que no.",
"Outlook no es tan bueno",
"Muy dudoso."
]```
import random
where do i put that
on very top
there is a way to implement auto help commands?
like if i add a command it join on a help command
bump
how do i fetch a member using an api call while using a discord member converter?
await commands.MemberConverter().convert(ctx, args: str)
and yes, read the docs
or pass : Member to your obj in the command params
Is there a way to loop through all @tasks.loop() tasks of my discord bot/cog? I want to loop through them in cog_unload and cancel/stop them. Would be easier than manually writing a cancel for each one :)
task.loop is for something thats repeatedly looped, u dont want that for cogs
wdym?
I mean, it is constructed like discord.Embed(title="** **") ?
And like just use the embed.set_author?
its hard to tell on mobile
Yeh me same
xxx's blackjack game is the author
'you didnt respond in time' is either bold in description or title
Why not? I have multiple loops implemented in my cogs and didn't run into serious problems so far... And this doesn't answer my question
here
it is embed.add_author right?
to make that embed we need to make title="** **" right?
@_change_prefix.error
async def _change_prefix_error(self, ctx:bridge.BridgeContext, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.respond(f'> **Error : Missing Required Argument - **`new_prefix`')
i get the error
Traceback (most recent call last):
File "C:\Python\lib\site-packages\discord\cog.py", line 715, in _load_from_module_spec
Traceback (most recent call last):
File "e:\Python\Evelynn Workspace\Evelynn7\main.py", line 28, in <module>
client.load_extension(f'cogs.{filename[:-3]}')
File "C:\Python\lib\site-packages\discord\cog.py", line 787, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Python\lib\site-packages\discord\cog.py", line 717, in _load_from_module_spec
del sys.modules[key]
KeyError: 'cogs.setup_cog'
_change_prefix -
@bridge.bridge_command(name = 'change_prefix', description = 'Change the prefix for your server')
@commands.has_permissions(administrator = True)
async def _change_prefix(self, ctx:bridge.BridgeContext, new_prefix:discord.Option(str, description = 'New prefix for your server')):
mongo.guild_profiles.update_one({'_id' : ctx.guild.id}, {'$set' : {'prefix' : new_prefix}})
await ctx.respond(f'Prefix for `{ctx.guild.name}` set to `{new_prefix}`')
i got ur question wrong mb
afaik loops don't stop when u unload them
and there's not a good way that i know of to start a loop thats in a cog that i know of, which can be enabled on cog load and disabled on cog unload
i could be wrong tho, take my words with a grain of salt
def __init__(self, bot:commands.Bot):
self.client:commands.Bot = bot
if self.do_checks.is_running():
self.do_checks.stop()
self.do_checks.start()
def cog_unload(self):
# To avoid errors, stop all running loops
loop: tasks.Loop
for loop in [self.do_checks]:
if loop.is_running():
try:
loop.stop()
except Exception as e:
log.error(f"{loop.__name__} {e}")
Working fine, would just be better to have something else than a manual list of all loops
Code in main file:
@tasks.loop(seconds=10)
async def updateactivity():
"""Updates the bot's activity"""
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=f"!help in {len(bot.guilds)} servers for {members(bot)} users."))
@updateactivity.before_loop
async def wait_for_ready():
"""Waits until the bot is ready"""
await bot.wait_until_ready()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.event
async def on_guild_join(guild):
# some code
bot.run(os.getenv('TOKEN'))
updateactivity.start()```
**Error:** my bot doesnāt have a status, no error shown.
Your updateactivity.start() will only be executed if your bot stops. Move it to the on_ready()
many tell me not to put stuff like these tasks or loops in on_ready() since on ready can be executed multiple times at once 
This is true, you can either do
if not updateactivity.is_running():
updateactivity.start()
``` or just put your ``updateactivity.start()`` right before ``bot.run()``. Not sure about this though, but ```py
@updateactivity.before_loop
async def wait_for_ready():
``` should handle this I think.
putting it before bot.run() worked for me, thank you :)
my bot responds 2 times to normal commands
everything else works
when I ping the bot it responds once
I noticed that a new command that I created recently works normally
you sure you don't have 2 of the same bot instance running lol
yes
i changed the token
i restarted my computer
this keeps happening for over 2 weeks now
someone ran it on his computer
and everything was fine
i even created a different bot
and it still didnt work
no
I have a slight issue, where uploaded files are kept in memory after being uploaded, kinda like a memory leak, does anyone know how to fix if possible?

