#General Help
1 messages · Page 26 of 1
Alright, I defo understood the case more
they can not just only act as switches but pattern matching as well
You don't need to worry about them if you aren't too good with the base of Python though
okay
Thanks, It works im going to customize it to what i was aiming for now
I am using py await interaction.response.edit_message("Helllo ") to edit the message.. (Default one)
Traceback (most recent call last):
File "C:\Users\jackd\Documents\Felbcord Py.venv\lib\site-packages\discord\ui\view.py", line 371, in _scheduled_task
await item.callback(interaction)
File "C:\Users\jackd\Documents\Felbcord Py\commands\helpmenu.py", line 33, in select_callback
await interaction.response.edit_message('Helllo ')
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given
I dont see 2 args??
Ooh i sorted it, I added content =
content=""
yeah
if it was an embed, would i use embed = as normal?
yes
alright
1st arg is interaction.response (implicit)
i got it dw
I know, I'm just trying to help you learn 🙂
Yeah, I appreciate it :D
That code would work fine, Are you trying to allow a certian role only or?
Hey, do you mind helping me here?
Modals = discord.Embed=(title="Modals Help",description="")
It says ( was not closed, but it litearly is at the end
So what are you needing help with?
What you gave works fine
send full code
full 'code'
:)
why do you send anything?
The ( is litearly closed at the end of description
Oh i see, a typo :/ i had discord.Embed=
on_raw_reaction_add im trying to check if the reaction author is the same as the message author and if so delete it
@client.event
async def on_raw_reaction_add(event: discord.RawReactionActionEvent):
channel = client.get_channel(event.channel_id)
msg = await channel.fetch_message(event.message_id)
if msg.author.id == event.user_id:
await msg.remove_reaction(event.emoji, msg.author)
replace client with bot if you use that
should payload be in the args?
wdym
@bot.event
async def on_raw_reaction_add(payload):```
yeah payload is the event
i added the reaction remove part i forgot to include that
the await msg.remove_reaction(event.emoji, msg.author) is what i needed, thanks!
How to enable slash commands for all users? They are only working for me and don't show up for others.
ty thought it would be by defaul;t
is there any way to get a role by its color
ive tried
role = discord.utils.get(ctx.guild.roles, name=ROLES.names[color], color=discord.Color(int(list(ROLES.colors[color][i].keys())[0], 16))) but for some reason its just, not executing? my code stops running w no errors once it reaches that line
How to make it so slash commands won't show up for the user when entering / unless they have a specific role
idk if it is even possible but this is the worst method to get role
what should I do
get role by id
It's possible 1 sec
roleColour = 0xFFC200 #change colour to desired one
for role in guild.roles:
if role.color == roleColour:
break
Wdym hacky xd
Utility = discord.Embed(title="Utility Command Help",description="Here is a list of FelBot's Utility related commands along with their infomation\n :arrow_right: `/ban` - Bans a user and will DM them the reason for their ban \n :arrow_right: `/bean` - Fake bans a member, Bans and unbans with an invite in dms \n :arrow_right: `/github` - Sends the github repo link \n :arrow_right: `/kick` - Kicks a member and sends them reason \n :arrow_right: `/membercount` - Sends the server member count without including bots \n :arrow_right: `/nick` - Changes another members nickname to CensoredNick \n :arrow_right: `/serverinfo` - Sends an embed about the server infomation/stats \n :arrow_right: `/slowmode` - Sets the channel slowmode \n :arrow_right: `/stats` - Sends the server infomation/stats \n :arrow_right: `/howtoverify` - Sends a youtube video showing how to verify with skykings \n :arrow_right: `/help` - Sends infomation about the bot and select menu for help commands \n :arrow_right: `/suggest` - Opens a modal for your suggestion and sends to suggest channel ", color =discord.Color.blue())
Fun = discord.Embed(title="Fun Commands Help", description="Here is a list of FelBot's Fun related command and their infomation \n :arrow_right: `/dm` - DM's a member with the message of your choice \n :arrow_right: `/rickroll` - Sends the member a rickroll \n :arrow_right: `/say` - Sends a message of your choice ",color = discord.Color.blue())
Embeds = discord.Embed(title="Embeds Help", description="Here is a list of FelBot's Embeds that are run through commands and includes what they do \n :arrow_right: `/apply` - Sends the apply info embed \n :arrow_right: `/BotRules` - Sends FelBot's rules \n :arrow_right: `/perks` - Sends the perks/info of level roles, boosting,staff roles and extra roles \n :arrow_right: `/rules` - Sends felbcord rules ",color = discord.Color.blue())```
one sec
W
it a big msg i have question but its too big code lmao
class Help(discord.ui.View):
@discord.ui.select(
placeholder = "Choose a category",
min_values = 1,
max_values = 1,
options = [
discord.SelectOption(
label="Fun Commands",
description="Click here to see help on the Fun Commands"
),
discord.SelectOption(
label="Utility Commands",
description="Click here to see help about Utility Commands"
),
discord.SelectOption(
label="Embeds Help",
description="Click here to see help about Embeds"
)
]
)
async def select_callback(self, select, interaction):
match select.values[0]:
case "Fun Commands":
await interaction.response.edit_message(embed=Fun)
case "Embeds":
await interaction.response.edit_message(embed=Embeds)
case "Utility Commands":
await interaction.response.edit_message(embed=Utility)
Embeds returns, Interaction faild
failed
why?
Its all right, Both other select menus work.
Idk
hmm
Ah i see my issue
await ctx.respond(self.bot,embed=info view=Help())
Says ( is not closed when it is?
I think i sorted it
(ignore nick) I am using random choice and its only changing it if i change the member im aiming it on
@slash_command(name='payrespect',description='Say command')
async def payrespect(self, ctx,member: discord.Member) -> None:
c1 = 'hello'
h ='hi'
await ctx.respond(random.choice([c1, h]))``` (This code is just so i can figure out how to do it, not my actual code)
ping me if u reply
So it isn't wrong just bad luck?
How so
youre just setting them as constants
I'm just having it so it changes what it sends each time
thats dependent on the list
not the variables
again this is in the given context
i cant read your mind
any ideas how to put all mentions in a slash command into a list?
bump[
nobody can really help without seeing your code
@commands.command()
@commands.is_owner()
async def colorroles(self, ctx):
# cover_images = ROLES.cover_images
# colors = ROLES.colors
await ctx.guild.create_role(name="white", color=discord.Color(0xFFFFFF))
``` that's all there is to it
just the basic create_role function is hanging
does anyone know what kind of view this is using to format a message like this?
embeds?
does anyone know why the rows 2 & 3 aren't formatted the way they're titled?
@client.command()
async def embed_test(ctx):
embedVar = discord.Embed(title="Title", description="Title Description", color=0xFF0000)
embedVar.add_field(name="Column 1 Row 1", value="description", inline=True)
embedVar.add_field(name="Column 2 Row 1", value="description", inline=True)
embedVar.add_field(name="Column 1 Row 2", value="description", inline=False)
embedVar.add_field(name="Column 2 Row 2", value="description", inline=True)
yep that was exactly what I was looking for
thanks
I tried to add an empty field as a placeholder but that didn't work
embedVar = discord.Embed(title="Title", description="Title Description", color=0xFF0000)
embedVar.add_field(name="Column 1 Row 1", value="description", inline=True)
embedVar.add_field(name="Column 2 Row 1", value="description", inline=True)
embedVar.add_field(name="", value="", inline=False)
embedVar.add_field(name="Column 1 Row 2", value="description", inline=True)
embedVar.add_field(name="Column 2 Row 2", value="description", inline=True)
this is the way I want it to be formatted but it looks like there has to be a field in between with inline=False and it doesn't take \n for the title & description fields
does anyone know a way around this?
I guess the answer is
embedVar.add_field(name="\u1CBC", value="\u1CBC", inline=False)
seems clunky though
yeah you can't format it that way without using some type of invisible characater
which may look clunky on mobile because embeds are always one field per line
Also I'd suggest making your variables snake case (snake_case) instead of camel case (camelCase)
It's not required or anything, it's just what most people prefer
some IDEs like Pycharm may throw a fit because of it
bump?
what permission does a bot need to send message in a read only channel ?
I gave the bot this
changing to spongebob case just for you
what
This is an English server. We can't read that.
I put Send message permission
for the bot
in the channel menu
but I still get missing permission
eMbedvaR = discord.Embed(title="Title", description="Title Description", color=0xFF0000)
oh god

Hey there, I have been trying to use the edit_role_positions() function. I just want to know, how I can set the role to the Highest possible value allowed by the Bot's Roles?
probably get the bots role position and then add 1
The reactions list is fairly straightforward to access, it contains a list of reactions objects on a message. However, the reactions objects simply contain the number of reactions, not the users that reacted to them. What is the correct way to generate a list of users that reacted to a message as well as what their reactions were?
I want my bot to perform an action on a specific time how can i do that?
Here's the background task asyncio example.
Here's the background task example.
#969580926885580801 message this one
code: ```py
@bot.command()
async def testin(ctx, user: discord.Member = None):
my_image = Image.open("wanted.jpeg")
asset = user.avatar.with_size(128).url
data = BytesIO(await asset.read())
pfp = Image.open(data)
pfp = pfp.resize((125, 125))
my_image.paste(pfp, (36, 80))
my_image.save("profile.jpg")
await ctx.send(file=discord.File("profile.jpg"))```
error: ```pyIgnoring exception in command testin:
Traceback (most recent call last):
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 181, in wrapped
ret = await coro(*args, **kwargs)
File "/Users/luke/PycharmProjects/pythonProject4/main.py", line 1916, in testin
AttributeError: 'str' object has no attribute 'read'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 344, in invoke
await ctx.command.invoke(ctx)
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/Users/luke/PycharmProjects/bot/venv/lib/python3.10/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: AttributeError: 'str' object has no attribute 'read'```
how can i fix? thx
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 :)
asset = user.avatar.with_size(128).url
data = BytesIO(await asset.read())
pfp = Image.open(data)
``` your ``asset`` is a string and you try to read it. You need to download the file and convert it to an Image
```py
import requests
asset = user.avatar.with_size(128).url
data = requests.get(asset, stream=True)
pfp = Image.open(data.raw)
so uh I've made view for my button and I want to make it so whenever they click the button it adds their ID to a list
Where can i find examples of embeds?
Fairly new with pycord, just wondering how can I get my bot to send messages to a channel when a member leaves or joins?
async def on_member_remove(self, ctx):
embed.add_field(name = "User left!", value= f"The User has left!")
await ctx.respond(embed=embed)
That's what I currently got
Have a client event
well for one what embed are you even referring to
You mean @bot.event?
Yea
I do have that and embed is also defined
@bot.event
async def on_member_remove(self, ctx):
embed.add_field(name = "User left!", value= f"The User has left!")
await ctx.respond(embed=embed)
Embed isn't defined
embed = discord.Embed(
color=discord.Color.blurple())
embed.set_footer(text="Created by TechSly")
embed.set_author(name="Techsly", url="example"
embed.set_thumbnail(url="example")
Sorry I forgot to add these in
Oh yeah that works
I was wondering what I could do in order for the bot to send a message into a certain channel whenever a member leaves
ctx.channel would be the current channel
H
im guessing to define channel i would add channel = channel_id(0000):?
Channel = bot.get_channel('id')
Could I know which ones since currently I'm looking at the Api reference
H
well the pycord ones
No tag docs found.
Alright thank you
there a way to chanege the permissions for a specific member to view no channels except 1
?
Yeah that's what I'm on as well, but yeah I should probably read more of it
Thank you
Hello, is there a way to create autocomplete with webhooks?
Elaborate?

Hi there,
I'm having the following problem and I'm looking for someone who could possibly help me out. So I have a Cog named "CardsMain" in which I wanna run an async loop called mainLoop(). In this loop the bot is checking something every hour. I don't want the bot to sleep for an hour, that's why I'm using asyncio.sleep(). However I can only use that in an async function. I need this mainLoop to be called automatically every time even if I reload the Cog. Is there a listener for something like Cog.load() in which I can call async functions? Or where can I call it from?
class CardsMain(commands.Cog):
def __init__(self, client):
self.client = client
async def mainLoop(self):
# do something
await asyncio.sleep(3600)
def setup(client):
client.add_cog(CardsMain(client))```
on_ready() gets called more than one time so I skip on that
wouldn't it be easier to use a task
^ this
does custom emojis not work in embeds?
Maybe you start reading the discord docs.
Custom emojis > depends on <@&881207955029110855> permissions if send via webhook.
#990976678954147910 help
Would emphermals work in bridge commands?
yes, but only bridge equivalent of application context
Wym bridge equivalent?
ty will see it now
I cant see anything here talking about empheramls, (ik spelt very wrong), I can only see defer, edit, delete respond, reply ect
BridgeContext is an abc. BridgeApplicationContext inherits from BridgeContext, and only BridgeApplicationContexts can use ephemerals
alright
So this allows modals, correct?
Would i need to add alot of this to my code to allow BridgeApplicationContext
If you can do it with ApplicationContext, you can do it with BridgeApplicationContext
Yeah but i've got this right now
@bridge.bridge_command(name="rickroll", description="rickrolls someone")
@commands.cooldown(1,10, commands.BucketType.user)
async def dm(self,ctx,member: discord.Member):
message = ('https://tenor.com/view/rickroll-roll-rick-never-gonna-give-you-up-never-gonna-gif-22954713')
await member.send(message)
await ctx.send(f'{member} has been rickrolled', ephemeral=True)``` but it says unexpected ephemeral, what would i have to add?
You make sure it is a BridgeApplicationContext then send it ephemerally with ctx.respond
ctx.respond or ctx.reply
@bridge.bridge_command(name="rickroll", description="rickrolls someone")
@commands.cooldown(1,10, commands.BucketType.user)
async def dm(self,ctx:BridgeContext,member: discord.Member):
isinstance(ctx, BridgeApplicationContext):
command_type = "Application command"
message = ('https://tenor.com/view/rickroll-roll-rick-never-gonna-give-you-up-never-gonna-gif-22954713')
await member.send(message)
await ctx.send(f'{member} has been rickrolled', ephemeral=True)``` I tried this but i just have BridgeContext is not defined and expected expression, I am looking at the docs
Here's the background task example.
from discord.ext.Bridge import BridgeApplicationContext
from discord.ext.Bridge import BridgeApplicationContext``` Import bridgeapplicationcontext could not be resolved, do i need another import for this to work?
Why does that not work?
Any ideas?
Its just that but without the emoji and any errors
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 :)
Looks like you don't differentiate between == and =
so i have to use = and not ==?
anyone?
if you compare you use == and if you assign you use =
if 5 == 5:
a = 5
lowercase the Bridge
Thank you, Do you know why i also have the 'Expected expression'
It seems right to me
elif without if?
lol
lol?
and without indent
it literally marks your mistake
expected indent block bruh
#help-rules
- Learn Python - Pycord is a complex library that requires you to know Python concepts like OOP, async-await, etc. Run ?tag lp to find resources where you can learn Python.
Looks like you should learn Python a little bit ;)
I know it but sure
@bridge.bridge_command(name="rickroll", description="rickrolls someone")
@commands.cooldown(1,10, commands.BucketType.user)
async def dm(self,ctx,member: discord.Member):
if isinstance(ctx, BridgeExtContext):
command_type = "Traditional (prefix-based) command"
elif isinstance(ctx, BridgeApplicationContext):
command_type = "Application command"
message = ('https://tenor.com/view/rickroll-roll-rick-never-gonna-give-you-up-never-gonna-gif-22954713')
await member.send(message)
await ctx.send(f'{member} has been rickrolled', ephemeral=True)``` I no longer have errors, but i do when testing the command
Traceback (most recent call last):
File "C:\Users\jackd\Documents\Felbcord Py\.venv\lib\site-packages\discord\ext\commands\bot.py", line 344, in invoke await ctx.command.invoke(ctx)
File "C:\Users\jackd\Documents\Felbcord Py\.venv\lib\site-packages\discord\ext\commands\core.py", line 927, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\jackd\Documents\Felbcord Py\.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: Messageable.send() got an unexpected keyword argument 'ephemeral'
This is the same as the examples
Here's the bridge commands example.
hmm
https://docs.pycord.dev/en/master/api.html?highlight=send#discord.abc.Messageable.send
send doesn't have ephemeral.
Afaik ephemeral only exists for responses
Ah alright
I had send cause before i was told about this, I thought respond wouldnt work lol
xD
Context has no attrubite respond, Works normaly?
I think you need to split after your command type. ctx from normal command isn't an interaction so you can't respond
But I can only guess, never really used them slash commands
How can i get a users custom status?
How would i split? and would it be between the command_type and elif
You already made the split with the if/elif, now you just need to code your desired response/message within these blocks
@bridge.bridge_command(name="rickroll", description="rickrolls someone")
@commands.cooldown(1,10, commands.BucketType.user)
async def dm(self,ctx: bridge.BridgeContext,member: discord.Member):
if isinstance(ctx, BridgeExtContext):
message = ('https://tenor.com/view/rickroll-roll-rick-never-gonna-give-you-up-never-gonna-gif-22954713')
await member.send(message)
await ctx.respond(f'{member} has been rickrolled', ephemeral=True)
elif isinstance(ctx, BridgeApplicationContext):
command_type = "Application command"``` like this?
@steep bluff
It dosent work, but i dont even have an error??
🤷
If you use it as Application command there should be no error (because you only assigning a variable).
Why does it not say "No custom Status"? what did i do wron? pls help
Should i make a new thread? for it
ima do it lol
activity is your activity (what you are playing/listening to/watching) and not the custom status
but i didnt find anything expect raw_status but thats just online or offline etc.
so
what is the variable
for the custom status from smn
I want to import a package to a cog. I tried using import package, but it didn't work.
do you know how to get a custom status?
no
how can i disable a button after one use
no
Is it possible to send posts from a certian reddit account instead of sending certian posts from it?
so no need to specify the post links, just the account link
pls help
Is this what you're looking for?
nah thats just Online, Offline, Dnd and Idle
not custom status
Dont think you can
Bruh for real?
I cant confirm it, But i cant see anything on the docs related to it
(api refrence)
F
how do i remove the "this interaction failed" thing?
But it works when i have a status in
... code
What did you use for that?
(code)
But without its that
nah i have the bot send a response using the typical ctx.send thing, it sends a response, then discord says failed anyway
activity = member.activity
if activity is None:
activity = 'No custom Status'
# Define Embed
embed = discord.Embed(title=f'Userinformation ➥ {member.name} {memberstatus}',
description=f'Here is all the information about {member.mention}:',
color=0xa0522d)
embed.add_field(name='Name ▼', value=f'{member.name}', inline=False)
embed.add_field(name='Joined ▼', value=member.joined_at.strftime('%d. %B %Y at %H:%M'), inline=False)
embed.add_field(name='Account created ▼', value=member.created_at.strftime('%d. %B %Y at %H:%M'),inline=False)
embed.add_field(name='Status & Custom Status▼', value=f'➤ Status: {memberstatus1} ➤ Custom Status: {activity}',inline=False)
embed.add_field(name='Nickname ▼', value=member.nick, inline=False)
embed.add_field(name='Highest Role ▼', value=member.top_role.mention, inline=False)
we still need the code...
ill send an extract
use codeblocks
sry
yeah
activity = member.activity
if activity is None:
activity = 'No custom Status'
# Define Embed
embed = discord.Embed(title=f'Userinformation ➥ {member.name} {memberstatus}',
description=f'Here is all the information about {member.mention}:',
color=0xa0522d)
embed.add_field(name='Name ▼', value=f'{member.name}', inline=False)
embed.add_field(name='Joined ▼', value=member.joined_at.strftime('%d. %B %Y at %H:%M'), inline=False)
embed.add_field(name='Account created ▼', value=member.created_at.strftime('%d. %B %Y at %H:%M'),inline=False)
embed.add_field(name='Status & Custom Status▼', value=f'➤ Status: {memberstatus1} ➤ Custom Status: {activity}',inline=False)
embed.add_field(name='Nickname ▼', value=member.nick, inline=False)
embed.add_field(name='Highest Role ▼', value=member.top_role.mention, inline=False)
better?
xd
yes
Discord interaction need a respond to avoid interaction failed
why not use {membertstaus1}?
class main_menu(discord.ui.View):
def __init__(self, bot, ctx):
super().__init__(timeout=60)
self.context = ctx
self.bot = bot
@discord.ui.button(label="Age", style=discord.ButtonStyle.red)
async def age(
self, button: discord.ui.Button,interaction: discord.Interaction
):
from age import age
await age(bot=self.bot,message=self.context)
age sends messages.
im guessing i need to pass an interaction object for it to respond to?
where are u respoonding there
You can igonore it using .pong method
thats what i needed thanks
Note: if it triggered twice/pressed twice, itll raise alrady respond
I want to import a package to a cog. I tried using import package, but it didn't work.
But the interaction failed thingy wil be apear again 
I guess
Idk
does anyone know how to access which users have reacted to a message? I expected the reactions objects to contain a list of users but it does not. I'm passing in discord.Intents.all() so that shouldn't be it
there must be a way the data is right here
@bridge.bridge_command()
async def avatar(self, ctx, member: discord.Member) -> None:
await ctx.send(member.avatar_url)``` why dosent this get the users avatar?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Member' object has no attribute 'avatar_url'
avatar.url
use ctx.reply or ctx.respond
and message.reactions
it's not in message.reactions
but discord.Reaction.users() returns an AsyncIterator which can be flattened to a list
I'm looking at the debugger right now there isn't a list of users in that object
It's not an attribute
so what is it lol
if you read the docs it will make sense
U
that was the correct documentation, thanks!
idk why I couldn't find that in the docs yesterday, must have just needed sleep
you can ask reddit "_"
Shouldn't pycord discord know tho lol
no, because not everyone uses reddit
Tru
Hi, how can I make slash commands only for some servers with an array of the server ids
How I can get user's connected accounts?
only register the slash commands in those guilds
but how
can I put in guild_ids=servers]
?
and servers = [653465784356783456, 981237860734742539]
yes
as long as it's syntaxically correct
lemme try then
I want to import a package to a cog. I tried using import package, but it didn't work.
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
No tag idw found.
bruh
I think that it's clear that the error is package not found
yes, but are you going to send the code or not
I want to import the package to the cog
i tried usign import config but it didnt work
then do import ..config
import ..config
^
SyntaxError: invalid syntax
is the error on the . or the n
Try from .. import config
literally what I said
;-;
how do you edit permissions for a channel for a mentioned member?
was thinking about something like that then forgot the actual syntax. I should do more python
thanks
waitg
If I use from .. import config then it shows
discord.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: ImportError: attempted relative import beyond top-level package
If I use from . import config it shows
discord.errors.ExtensionFailed: Extension 'cogs.moderation' raised an error: ImportError: cannot import name 'config' from 'cogs' (unknown location)
i believe its relative to where the script is started from
it didnt work
unknown module
File "d:\Desktop\peer\cogs\event.py", line 5, in <module>
import config
ModuleNotFoundError: No module named 'config'
you may have a problem with your module hierarchy then ¯_(ツ)_/¯
which requires a complete restructuring
it means your folder structure that holds everything you need is fucked where you have to restructure it to fix it
what do I have to do
maybe its not as bad as i thought
I just put everything in a folder
works like a charm
@bridge.bridge_command(name='meme',description='meme command')
async def stab(self, ctx) -> None:
REDDIT_ID= 'GYz8WGvFclsP9LCMYmusOw'
SECRET_KEY=(os.getenv('REDDIT'))
auth = requests.auth.HTTPBasicAuth(REDDIT_ID, SECRET_KEY)
data = {
"grant_type": "password",
"username":"BlueFoolish",
"password": (os.getenv('REDDIT_PASSWORD'))
}
headers = {'FelBot': 'MyAPI/0.0.1'}
res = requests.post('https://www.reddit.com/api/v1/access_token',
auth=auth,text=data,headers=headers)
SECRETS = res.text()``` Why isnt res.text or res.json showing me the access token?
ok now it doesnt load the cogs
ask reddit
File "d:\Desktop\peer\bot.py", line 28, in <module>
client.load_extension("cogs." + filename[:-3])
ModuleNotFoundError: No module named 'cogs'
just a heads up, the requests module is heavily blocking, this is a problem when reddit is slow, and takes longer to answer your request
How so? Im new to the reddit api
this means your bot will hang while waiting for a response from reddit
Oh.. thats defo not good
if in the situation that reddit is, say getting ddosed
How would i fix this?
I am just trying to connect to the reddit api to take posts from subredits
take a look at aiohttp
Thanks i will read this now, whats it used for?
asynchronous requests
Is all i need to do is pip install it and import it
sync = waits for task to complete before outputting
async = multitasks and does everything at the same time, returning when done
ah alr
?
yes, pretty much
alright
you can skip the install part. pycord depends on aiohttp to function so you can just import it
alr
how would you remove all the roles of a member and store the list of role in a file and readd the roles back?
#Remove Role
#get member object
for role in member.roles:
"""store role.id in a database perferably with the key as the member.id since it would be more convient."""
await member.remove_role()
#Add Role
#get member object
for role_id in database:
#database is just a placeholder on how you will return the list of roles that were saved
role = ctx.guild.get_role(role_id)
await member.add_role(role) ```
how do I sent a message to a certain channel when an event gets called?
channel = client.get_channel(channelid)
await channel.send()
thanks
try
i.name + ", "
pretty sure before.roles is a list of Role Objects
an you cant concatenate a object with a string
Hey guys,
need a bit of a help, I need to clone an entire server. meaning all channels, roles and categories. Any help with that?
you can probably do that by looping over guild.channels and guild.roles
so on each loop you would create a new channel/role with the same info, permissions, etc.
how do i get the server owner ID, server owner tag, server name, server ID, server member count, and server invite using {guild…}?
You can read the docs
https://docs.pycord.dev/en/master/api.html#guild
what’s the difference between {guild.members} and {guild.members_count}?
on_member_leave takes a discord.Member, not a Context
One is a list of discord.Members, while the other is simply an int
thank you!
yes but lets say I have the roles in guild.roles, how do I clone in the the other server ctx for example?
b!rtfm pyc guild.create_
discord.Guild.create_category
discord.Guild.create_category_channel
discord.Guild.create_custom_emoji
discord.Guild.create_integration
discord.Guild.create_role
discord.Guild.create_scheduled_event
discord.Guild.create_stage_channel
discord.Guild.create_sticker
discord.Guild.create_template
discord.Guild.create_text_channel
is there any way to get the owners tag (example: Chaze#5125) and guild invite using this? i can’t see any way of doing so
new_guild = await client.fetch_guild(new_guild_id)
for role in ctx.guild.roles:
await new_guild.create_role(name = role.name, permissions = role.permissions, color = role.color)
guild.owner returns a member object. you can get the tag from the member object
guild has an invites coro
https://docs.pycord.dev/en/master/api.html#discord.Guild.invites
i mean like an invite to the guild, not already made invites from other users?
from when my bot joins
like can it create an invite upon joining?
idrm which channel it goes to
just an invite from the guild will do
For categories I am doing this:
for category in guild.categories:
category = await ctx.create_category(name = category.name)
``` Now how do I add channels in this category?
I have just two issues here:
(a)get channels in a category
(b) create a channel in a category
so what you want to do is create another for loop that loops through the categories channels
in await ctx.guild.create_text_channel you can pass the category you made into the category parameter
then you can get the category object and create text channels
so something like
for category in guild.categories:
await guild.create_category(name = category.name)
for channel in categories.channels:
if isinstance(channel, discord.TextChannel):
await category.create_text_channel(name=channel.name)
elif isinstance(channel, discord.VoiceChannel)
. . .```
@slender lintel how can I know to which category a channel belongs to ?
uh
channel.category
yeah
Okay okay okay.
I'll see to it.
Thank you fam. This community won't be anything without you guys.
np
I’m abit confused?
hi = await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None)
^
SyntaxError: invalid syntax
i am also confused at what I’m doing
I can see that
😂
here’s my full code:
@bot.event
async def on_guild_join(guild):
hi = await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_event=None, target_type=None, target_user=None, target_application_id=None)
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}")
you do know python right?
ish
thats not how you're supposed to call the create_invite function
docs confused me even more though
I realised
how do i
create_invite is an attribute of the object discord.Guild
on_guild_join() takes one parameter which is guild
so
you have the guild object already
you can then do invite = await guild.create_invite()
Also btw not to be mean or anything, but you should learn a little bit more classes and out they work. Since pycord really isn't a basic library.
oh right
?tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
here are some sources you can use to learn
for sure, once I’m finished with fixing this then I’ll take a look at the sources, appreciate the feedback :)
np happy to help
What does this mean?
jem.set_description(f"Server owner ID: {guild.owner_id}
^
SyntaxError: EOL while scanning string literal
you forgot to put the end quote
use \
or
"""""""
so like
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}")```
or
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}""")```
or
jem.set_description(f"Server owner ID: {guild.owner_id}"
f"Server owner tag: {stuff.tag}"
f"Server name: {guild.name}"
f"Server ID: {guild.id}"
f"Server member count: {guild.member_count}"
f"Server invite: {hi}")```
actually last one might not work 🤔
whenever I want to mention someone as the parameter of a slash command on Android mobile it gets rid of the whole parameter field. after selecting the mention from the autocomplete it just gets rid of the 'user' parameter field. is this intended behavior? am I doing something wrong? how should I get around this? any help would be appreciated, thanks in advanced
can I see your code
ty
that fixed that error
now I get this:
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 32, in on_guild_join
hi = await guild.create_invite()
AttributeError: 'Guild' object has no attribute 'create_invite'
oh yeah i forgot
create_invite is a channel thing
you would need to get a channel from the guild
by using the guild.channels which returns a list of channels in the guild
and just choose any of them
would look something like
invite = await guild.channels[0].create_invite()```
are you trying to mention anyone who is in the guild?
or only a specific group of people that is in your autocomplete
the code for the slash command function is just this:
@bot.slash_command(name="givebonk")
@commands.check_any(permissions.is_mod(), permissions.is_dev())
async def give_bonk(ctx: discord.ApplicationContext, user, charges):
await fun.give_bonk(ctx, user, charges)
and in fun.py
async def give_bonk(ctx: discord.ApplicationContext, user, charges):
# Extract and validate user id from input
match = re.fullmatch(r'<@!?([0-9]{15,20})>', user)
user_id = int(match.groups()[0]) if match else None
if user_id is None:
await ctx.respond(f'Invalid user {user}', ephemeral=True)
return
# Check if charges is a valid int
try:
charges = int(charges)
except TypeError:
await ctx.respond(f'Invalid amount of charges', ephemeral=True)
return
# Add bonk charges to firebase
Config.db.collection('commands').document(f'{user_id}').set({'bonk': firestore.firestore.Increment(charges)},
merge=True)
# Give feedback about given bonks
await ctx.respond(f'Gave {user} {charges} bonks', ephemeral=True)
# Notify that the user that they've been given bonks
await ctx.send(f'{user} suddenly feels a _deep_ need to a thwack people...')
it has also occured to me that i should have put this in its own post, ill be doing that shortly
just anyone that is in the guild
oh
one sec ill give you an example on what you should do
instead of using auto complete
@slash_command(name="bonk")
async def bonk(ctx, user: discord.Option(discord.Member, "choose a member to bonk"), charges: int):
await ctx.respond(f'Gave {user} {charges} bonks', ephemeral=True)
# Notify that the user that they've been given bonks
await ctx.send(f'{user} suddenly feels a _deep_ need to a thwack people...')```
when you type hint it with discord.Member
it automatically gives you the autocomplete for all the members in the guild
don’t mean to interrupt you guys, so sorry if I am, but I get a 404 Not Found Unknown Channel error, when the guild i invited my bot to clearly does have channels
thank you so much, i will try this and get back to you!
print our guild.channels
see what it returns
i have no idea about this sorry
maybe you can't access the guilds channel from the guild object from the on_guild_join event
oh right, is there any other way?
it’s completely fine if you don’t know, sorry for being a pain aha
how do you respond to a slash command with an ephemeral message it should be possible i believe but i can't find any documentation on this
dont know sorry
await ctx.respond(ephemeral=True)
ah alright, no problem, thanks for the help
^ if anyone else knows, please let me know
wait yeah it sent as normal sadge
are you defering anything?
await ctx.defer(ephemeral=True)

@slender lintel How can I get guild by ID?
I am using bot.get_guild(id) but its giving NoneType error
if it is giving NoneType it probably means that the guild wasnt in the cache
so you need to fetch it which makes an api call
Any specific reason why guild.categories is returning an empty list?
@slender lintel
sorry i dont
Is there a way to update the choices of a slash command once the bot is running?
Here's the slash autocomplete example.
guilds intent maybe?
I think this is what you want @fresh brook
It should be in applications/<id>/bot right?
I can't seem to find it.
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
on_error catches any exception right. For example, a button's callback failed
yes I did that.
If it failed in your code. (Not the discord message if it did not respond in time EX "The application did not respond")
Yeah yeah. Like a button's callback raises discord.Forbidden (example)
It would catch it right
yup
Does it ignore on_command_error's or also raises there
and guilds= True?
Otherwise the guild might not have any categories.
wait i think i know why. Give me a seconds
I set discord.intents.all() I think this should do it right?
yes
According to plun
discord doesn't provide guild channel data when you fetch it directly from them
so you should use.
https://docs.pycord.dev/en/master/api.html?highlight=applicationcontext#discord.Guild.fetch_channels
than you can loop through it comparing the types and seperate the catagories.
I think you need to tell it to look at on_command_error first than procede. There is an example let me find it
was more looking if it was possible to update it in realtime.
Like adding options while the bot is live
unless the choices are unchangeable once the bot is running
@fresh brook I have been trying to clone a server for 2 hours now, Here's my code but can't seem to get either channels or categories. Idk what's wrong please help.
@bot.command()
async def clone(ctx, id):
print('Cloning guild: ' + id)
try:
for channel in ctx.guild.channels:
await channel.delete()
for category in ctx.guild.categories:
await category.delete()
for role in ctx.guild.roles:
if role not in ctx.guild.get_member(bot.user.id).roles:
await role.delete()
except:
print('Error')
guild = await bot.fetch_guild(id)
print(guild)
for role in guild.roles:
await ctx.guild.create_role(name = role.name, permissions = role.permissions, color = role.color)
print(guild.name)
print( await guild.fetch_channels())
#print("Here")
#for category in guild.categories:
#cat = await ctx.guild.create_category(name = category.name, position = category.position)
```
@ancient gazelle
Oh, id appreciate that
Yes autocomplete can happened real time. However it does not guarantee the user chooses one of the items. You could update the slash command and sync it but i dont think this is intended to be done often
but print( await guild.fetch_channels()) should give me channels right?
uh
Idk if the code is even running there. It just comes to a halt.
what is the last thing that is pritned after running the command?
The server name
@ancient gazelle
for channel in old_guild:
await new_guild.create_text_channel(channel.name)
an idea
Tried. but can't get any luck there.
it give an error?
yes.
what error?
wait I'll send the traceback
@fresh brook @worthy basin I might have come upto something
@bot.command()
async def clone(ctx, id):
print('Cloning guild: ' + id)
try:
for channel in ctx.guild.channels:
await channel.delete()
for category in ctx.guild.categories:
await category.delete()
# for role in ctx.guild.roles:
# if role not in ctx.guild.get_member(bot.user.id).roles:
# await role.delete()
except:
print('Error')
guild = await bot.fetch_guild(id)
for role in guild.roles:
print('Creating role: ' + role.name)
await ctx.guild.create_role(name = role.name, permissions = role.permissions, color = role.color)
for channel in guild:
await ctx.guild.create_text_channel(channel.name)
print("Here")
#for category in guild.categories:
#cat = await ctx.guild.create_category(name = category.name, position = category.position)
``` Changed the code to this and this is what I get as an output
Creating role: @everyone```
And it just stops
because it makes the @ everyone role
for role in guild.roles:
try:
await ctx.guild.create_role(name = role.name, permissions = role.permissions, color = role.color)
except:
print("Could not make role" + role.name)
else:
print('Creating role: ' + role.name)
Also, the @everone role is not created
No, like the code isn't running after this for some reason.
No errors?
@ancient gazelle
Changing to fetch_roles, maybe roles aren't cached
but even if it can't an error message must be displayed.
use the try/except inside the for statement
It was an old example that appears to no longer exist :/
But than I remembered that we have a newly updated one lol
https://guide.pycord.dev/popular-topics/error-handling
the thing is that, the bot isn't executing any statement after the statement
await ctx.guild.create_role(name = role.name, permissions = role.permissions, color = role.color)```
Execution just stops
Can't seem to figure out why
@worthy basin Any reasons why?
With no errors I have no idea why it would just stop
Doesn't look like there's an example of on_error
Oh, what was your question about it again?
.
If on_error ignores errors raised and caught by on_application_command_error or on_command_error
Docs define it as "Usually when an event raises an uncaught exception, a traceback is printed to stderr and the exception is ignored"
I looks like on_error is not related to command errors. So on_error will only run if it is not cought by any local handler. Not 100% on this tho
I think on_error is only errors from events
Thonk. Will have to try out
Is there a way to make guild-specific aliases
yes, but you will be on your own for most of this.
I'm hoping I don't have to mess with internal stuff?
I can make custom prefixes so I'd assume aliases work similarly, just not sure if there's somewhere I can pass the function to fetch a guild's custom aliases for each command
oh, I thought you meant slash commands
not slash no xD
then it should be much simpler.
yeah
what’s the use case?
an alias configuration command lol
b!rtfm pyc commands.bot.add_command
this would be useful
hm, this is not per guild right
you can add checks for them
Is everything under asyncronous function making an api call?
Like delete message, edit, send, etc...
If i do it excessively i will be rate limited right?
Is is possible to change the bot profile image and about me using code? If so then how?
not in a way that doesn’t violate tos (self-bot)
guys how can i make a slash command with number (8ball)
Hello everyone. I have been learning how to code in python from an online platform. I have an assignment which deals with text based files and string manipulation. I have been stuck with this assignment for 2 days, if anyone can help me out it would mean a lot. Please contact me if willing to help 😄
remove self
How can I get user's profile color
Its the most of the time way faster to google it
user.accent_color
it returned None
How can I do that, that it tells me the current time?
banner color
tysm!
oof then
?tag timestamps
No tag timestamps found.
?tag timestamp
No tag timestamp found.
?tag Timestamps
To make a timestamp you need a unix timestamp. Then, put your time and date into the converter and copy the "Unix Timestamp" (https://www.unixtimestamp.com/) Then to use the timestamp, follow this syntax: <t:COPIED_TIMESTAMP_HERE:FORMAT>
Where it says FORMAT, you can put a few different things:
R: Relative, says "two weeks ago", or "in 5 years"
D: Date, says "July 4, 2021"
T: Time, "11:28:27 AM"
F: Full, "Monday, July 4, 2021 11:28:27 AM"
Example: (note: 1000190514 is Unix time for 11 September 2001)
<t:1000190514:R> -> says 20 years ago
<t:1000190514:D> -> says 11 September 2001
<t:1000190514:T> -> says 12:11:54
<t:1000190514:F> -> says Tuesday, 11 September 2001 12:11
Epoch and unix timestamp converter for developers. Date and time function syntax reference for various programming languages.
i just switched from dpy to so im sorry if its a really stupid error.
bot = discord.Bot(debug_guilds=[991064945011621901])
@bot.slash_command(name="hello",description = "idk")
async def hello(ctx):
await ctx.respond("hello")
the error says that it faied to add the command to the guild
Can you show the full error. And also what version are you suing?
Failed to add command to guild 991064945011621901
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\amito\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 352, in _run_event
await coro(*args, **kwargs)
File "C:\Users\amito\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 793, in on_connect
await self.register_commands()
File "C:\Users\amito\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 343, in register_commands
commands = await self.http.bulk_upsert_guild_commands(
File "C:\Users\amito\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 332, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Acces
pycord dose not have a version 2.10
Make sure the bot has the create slash command permission and was invited with the application command scope
you have 2.0.0rc1 i think 2.10 was talking about a requirement for pycord. Anyways it is the latest version so you are good
oh alright
now im getting this discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
yh done that
and you reinvited the bot with the link?
yh
method 405 happens with a version older than rc1 or b7
oh nvm it loaded the command now
method 405 doesnt break the bot
it happens because permissions v1 was deprecated without notice
they are using the git release
hello, please help me here is the code
object = discord.utils.get(ctx.guild.roles, id = x[0])
button = Shop(label = object.name, ctx = ctx)
view = View()
view.add_item(button)
emb.add_field(
name = f" ",
value = f"**{x[4]}) {object.mention} \n Продавец: <@{x[1]}> \n Цена: {x[2]} :dollar: \n Куплена раз: {x[3]}**",
inline = False
)
await ctx.send(embed = emb, view=view)```
the bot gives an error
TypeError: Shop.__init__() got an unexpected keyword argument 'label'
Shop does not late a label argument when you are creating the button
and how then
def __init__(self, label, ctx):
super().__init__(label = label, style = discord.ButtonStyle.grey)
self.ctx = ctx
async def callback(self, interaction):
pass```
you're inheritting view not button
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
the code is this
update to rc
how
?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
how do i error handle slash cmds in cog?
What does this mean
log is a function for logarithms
its built in
and the only parameter is an integer
So I can't name it log?
You can do name="None"
Well your naming it None so wouldn't it be None
also why did u make it a string
Isn't it suppose to be a string?
i was making a kick command but i wwanted to make it so that theyhave to confirm it by clicking a button, how do i check if a user interacted wwitha button?
what exactly is lavalink/wavelink for? I was looking into using voice, and it says its for music playback, but I thought you could easily use discord.VoiceClient to for example play an audio file?
Its like a library that have built in music commands
...and whats the advantage of that over a normal VoiceClient?
the buttons have a callback method you can set
No advantage, it for people who want like simple music function join leave play stuff like that
If you want to do more advanced stuff you need to do it yourself
python random.choice only return the last element from the list after i run it a few time. Any idea?
Hi, just want to ask how do I add a cog to my bot?
The line your on goes in your cog
not main file
so where should I put it?
reconizing cogs
directories = ["./commands", "./Embeds","./Events","./Modals"]
for directory in directories:
for filename in os.listdir(directory):
if filename.endswith(".py"):
bot.load_extension(f"{directory[2:]}.{filename[:-3]}")```
Basic say cog command code
```py
from discord.ext.commands import slash_command
from discord.ext import commands
from discord.ext.commands import Cog
import discord
from discord.ext import bridge
class sayCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bridge.bridge_command()
async def say(self, ctx,message) -> None:
message = discord.utils.escape_mentions(message)
await ctx.send(message)
def setup(bot):
bot.add_cog(sayCog(bot)) ```
ok lemme try
can you format this..?
um i literally changed nothing and suddently i got a ```TypeError: init() missing 1 required positional argument: 'command_prefix'
command_prefix is needed when you call the commands.Bot class
You have to pass in a prefix
I want to check if the user mentioned an existing channel. How can I do that
mentioned aka #help-rules?
I tried searching
like, if there is channel "mention" in message you want to know if it exists?
yes
thanks
👍🏻
how do i get a server's banner
b!rtfm pyc guild.banner
and to get it into something you can process, banner.url
What does this error mean? py Ignoring exception in on_connect Traceback (most recent call last): File "C:\Users\orion\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 382, in _run_event await coro(*args, **kwargs) File "C:\Users\orion\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1042, in on_connect await self.sync_commands() File "C:\Users\orion\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 644, in sync_commands registered_guild_commands[guild_id] = await self.register_commands( File "C:\Users\orion\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 473, in register_commands prefetched_commands = await self.http.get_guild_commands(self.user.id, guild_id) File "C:\Users\orion\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 353, in request raise Forbidden(response, data) discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
update if you haven’t already then check
?tag missing-access
No tag missing-access found.
?tag missing_access
If you get a Missing Access (50001) error, you probably forgot to add the applications.commands scope.
To fix that, just replace YOUR_BOT_ID with your bot id and visit this link: https://discord.com/oauth2/authorize?client_id=YOUR_BOT_ID&scope=applications.commands
Hmm, I tried that but nothing changed.
len([m for m in ctx.guild.members]) it gives a error that says generator type doesn't have len()
I am trying to create a server cloning bot
async def create_categories(self):
for category in self.input_guild.categories:
overwrites_to = {}
for key, value in category.overwrites.items():
role = discord.utils.get(self.input_guild.roles, name=key.name)
overwrites_to[role] = value
new_category = await self.output_guild.create_category_channel(
name=category.name, overwrites=overwrites_to
)
await new_category.edit(
position=int(category.position), nsfw=category.is_nsfw()
)
log(blue+'[ServerCloner]'+r, f'Created category {cyan+str(category.id)+r}.')
self.created_map[str(category.id)] = new_category.id
Here's the cloning code. The only problem I am running is that I cannot copy permissions from the input server. Any problems that you can see?
@worthy basin Is there a problem here?
why bother remaking something that already exists?
doesn't create server template already do that?
Yes it does, but like this is part of a bigger project I am working on.
Consider this like a product/service that mutates your current server to a specific design as needed.
@slender lintel
wdym?
server template already exists
I guess see what roles people have store that information, create the new server (text channels, categories, voice channel), create the roles and then assign it? I guess that is how you will do it but I have no clue how you would code that best thing I did related to this is nuke a text channel
Idk if this will help but you can take a look at it
Is there an issue with images not being able to be on embeded messages?
shouldn't be. if you send your code, we might be able to help
Embed = discord.Embed(
title="Flight Announcement",
color=discord.Color.blurple()
)
for counter in range(5):
Embed.add_field(
name=Flight_Menu[counter][0],
value=Flight_Menu[counter][1],
inline=False
)
Embed.set_footer(
text="Hu",
icon_url="https://www.gannett-cdn.com/-mm-/05e97d16e7fb53439a4222e53dcba47d4d31dde8/c=0-97-1280-584/local/-/media/USATODAY/USATODAY/2014/06/04/1401911998000-AP-Color-Cosmos.jpg?width=3200&height=1680&fit=crop"
)
any errors?
and how are you sending it
await ctx.respond(embed=Embed)
if i remove the set_footer
it works perfectly fine
and if i add the footer, it doesn't work
mind sending the whole code so I can help you debug it?
sure
Flight_Menu = [ ["Flight Number","Delta-4763"],
["Departure | Arrival","Atlanta Int, GR | Haneda Int, Tokyo"],
["Boarding Time | Departure Time","12:50 BST | 13:00 BST"],
["Gate Number","Departure 2 | Arrival 4"],
["Aircraft Type","A380 / B777"]
]
@bot.slash_command(
name="test",
description="test",
)
async def test(ctx):
Embed = discord.Embed(
title="Flight Announcement",
color=discord.Color.blurple()
)
for counter in range(5):
Embed.add_field(
name=Flight_Menu[counter][0],
value=Flight_Menu[counter][1],
inline=False
)
Embed.set_footer(
text="Hu",
icon_url="https://www.gannett-cdn.com/-mm-/05e97d16e7fb53439a4222e53dcba47d4d31dde8/c=0-97-1280-584/local/-/media/USATODAY/USATODAY/2014/06/04/1401911998000-AP-Color-Cosmos.jpg?width=3200&height=1680&fit=crop"
)
await ctx.respond(embed=Embed)
does it take time for the command to take in>
take what in
also I think the jpg might be too large
or at least the wrong dimensions
Are you allowed to at a set a footer as an image and also it so big...
fro the image to get registered
I presume the link also works with Discord picture links well right?
yup
You shouldn't be waiting to a image to load in if so that could be a problem
no, that's on discord's side
just changed a few stuff up
@bot.slash_command(
name="test",
description="test",
)
async def test(ctx):
Embed = discord.Embed(
title="Flight Announcement",
color=discord.Color.blurple()
)
for counter in range(5):
Embed.add_field(
name=Flight_Menu[counter][0],
value=Flight_Menu[counter][1],
inline=False
)
Embed.set_image(
url="https://cdn.discordapp.com/attachments/939018232076062740/991434465270300783/Delta.png"
)
await ctx.respond(embed=Embed)
message in the Embed gets sent not the image
I don't think that gives an image
the discord link url?
ohh i see
If you were to click on the image yourself you should be able to see the image
I'll try to find ways to convert that image from discord thing, into an image link
if you send the image here
then I can convert it to a url
that you can use
if you don't mind
https://media.discordapp.net/attachments/969580926885580801/991457146174722128/Delta.png
this should work
yes perfect it does work
you can turn on developer mode
then you can click on the image
and then right click the expanded image
and click copy link
so this
awesome thanks for the help! I didn't know about that
np
How do i get all types of channel, like category and voice channel and text channel
@bot.tree.command()
async def get_id(interaction:discord.Interaction, channel:discord.VoiceChannel):
discord.abc.GuildChannel
this also includes category channels which you may or may not want
Ty
I am trying top recreate a verification bot that uses Buttons and Dropdown.
But apparently i am using slash commands and buttons wont work after restart.
I have looked the persistent example provided in the GitHub but i don't know how i can implement that for slash command since that's working for prefix command.
persistency doesnt apply to slash commands
so youre having some other kind of issue with those
discord limitation, you can’t
Modal is missing a lot of things 
discord says they are trying
Nice
is there a guide for voice record thats working?
none of them are working for me
help
Pycord tries to keep the recording of audio as simple and easy as possible, to keep making Discord
I noticed that bridge_commands fail when using send_modal - is it possible to send modals from normal commands (without an Interaction) or is that a discord limitation? cause I just found out views don't require slash commands, so just curious...
nope.
Is it possible to run a message through these filters too see if it goes against any.
although you can check which instance of the bridge context you have and adjust accordingly. e.x. having the user press a button for the modal
there might be some libraries that do those
hmmmm
I want to add a few webhooks that would end up being WebhookType.application compatible, how would i go about doing that for a couple of my bots, e.g. multiple tokens, multiple channels, so that i can add components
What is the best way to run un ending loop than using a while loop on on_ready () ?
@slow dome
discord.ext.tasks
I’m assuming it’s periodic
Is it not mandatory to add the repeat parameter ? ,
async def myLoop():```
here im looking for a solution without that
the time is enough
it will run as long as your code runs
my task can take nearly 10 - 15 min , so it wait for it to complete right ?
clear thanks
i think there is a parameter somewhere to change it
but yes, an error will appear and it will stop running
but you can catch that with @task_name.error
so it will cut the loop after 10 sec ?
no, it will try and run the loop every 10 seconds
so then it will create multiple threads ?
instead of waiting for the initial one to complete
no, async =!= threads
so the seconds = 10 , dosent matter at all
well, it's just the interval that it will try and run the task
awsm , so if the task is taking more than the interval it doesnt matter right ?
you still need to catch the error, but after that yes
ok , got it. what will be the issues if i run in on_ready and while loop
well, your bot can disconnect and reconnect and on_ready will be called again, for instance
ok so i need to call the task function inside on_ready ?
hello, how can i add a check in the play command of music bot to check if the bot actually joined the channel or not
my current code is
search = await wavelink.YouTubeTrack.search(query = query, return_first=True)
if not ctx.interaction.guild.voice_client:
try:
vc:wavelink.Player = await ctx.interaction.user.voice.channel.connect(cls = wavelink.Player, timeout = 10, reconnect = True)
except asyncio.TimeoutError:
return await send_error_embed("I couldn't connect to your channel", ctx)
await ctx.interaction.guild.change_voice_state(channel = ctx.interaction.user.voice.channel, self_deaf = True)
hello?
how can i put permission in Option
i wanted that in a slash command some option is available for some ranks
Hello, this should be pretty straightforward but I'm trying to figure out why this isn't working? All I'm doing is removing a role and kicking the user. I get an error telling me Application Command raised an exception: AttributeError: 'User' object has no attribute 'remove_roles' with the code being py async def kick(ctx, user: discord.Option(discord.SlashCommandOptionType.user, "Enter the person you wish to kick", required = True), reason: discord.Option(str, "Enter the Reason for kicking the user", required = False)): member_role = get(ctx.guild.roles, id=roleID) await user.remove_roles(member_role, reason="Kicked") await user.kick(reason = reason) return await ctx.respond("Kicked \o/", ephemeral = True)
change discord.SlashCommandOptionType.user to discord.Member
how do i get the member count
guild.member_count
tried this too, it gave the same error
you don't need to remove roles of the user, if they are kicked, the roles get removed automatically
same thing for channels right? like ctx.guild.categories_count would work
no
Oh, I thought that was only if they were banned. Well, that works then. Tyty
then how do i gett channels count
if you need to get category count , it will be len(guild.categories)
and for text channels: len(guild.text_channels)
guild.premium_subscription_count
oh alright
no no , there is a direct method for it
Hey I have a error but i didn't change my code. I only updated to the newest pycord version and now my bot isn't working anymore. Can someone help me?
This is the error when i tried to start my bot
raceback (most recent call last):
File "C:\Users\kingl\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 668, in _check_required_params
next(params)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Slash Commands\playground\main.py", line 2205, in <module>
playground()
File "c\Discord Bots\Slash Commands\playground\main.py", line 418, in __init__
async def help(ctx):
File "C:\Users\\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\bot.py", line 813, in decorator
result = command(**kwargs)(func)
File "C:\Users\\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\commands\core.py", line 1580, in decorator
return cls(func, **attrs)
File "C:\Users\\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\\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.
if your code is in a cog, you need to pass self parameter as well
along with the ctx
ctx.guild.premium_subscribers_count error: 'Guild' object has no attribute 'premium_subscribers_count''Guild'
its premium_subscription_count
not subscribers
no i want to get boosters count
if you want to know how many "people" boosted the server, it will be : len(guild.premium_subscribers)
oh alright
okay I'll try it out. Thank you
also i was doing a serer info command but if the server doesnt havve either a pfp,banner or banner it would give me an error,so i tried to handle itt by doing this:``` if ctx.guild.icon==None:
em.add_field(name="Display",value=f"No icon\nBanner\nSplash")
elif ctx.guild.banner == None:
em.add_field(name="**Display**",value=f"[Server icon]({ctx.guild.icon.url})\nNo banner\n[Splash]({ctx.guild.splash.url})")
elif ctx.guild.splash == None:
em.add_field(name="**Display**",value=f"[Server icon]({ctx.guild.icon.url})\n[Banner]({ctx.guild.banner.url})\nNo splash")
else:
em.add_field(name="**Display**",value=f"[Server icon]({ctx.guild.icon.url})\n[Banner]({ctx.guild.banner.url})\n[Splash]({ctx.guild.splash.url})") if ctx.guild.icon==None:
em.add_field(name="**Display**",value=f"No icon\n[Banner]({ctx.guild.banner.url})\n[Splash]({ctx.guild.splash.url})")
elif ctx.guild.banner == None:
em.add_field(name="**Display**",value=f"[Server icon]({ctx.guild.icon.url})\nNo banner\n[Splash]({ctx.guild.splash.url})")
elif ctx.guild.splash == None:
em.add_field(name="**Display**",value=f"[Server icon]({ctx.guild.icon.url})\n[Banner]({ctx.guild.banner.url})\nNo splash")
else:
em.add_field(name="**Display**",value=f"[Server icon]({ctx.guild.icon.url})\n[Banner]({ctx.guild.banner.url})\n[Splash]({ctx.guild.splash.url})")``` but its wrong
wait i think ik nvm
u should just keep it as str(banner.url) so if its none, it will just send a none, else it will send a valid link
ohh
await ctx.respond(embed=em)``` like this without if and else statements?
it gave me a nonetype oject has no attribute url error
oh ok, so just keep it as ctx.guild.banner.url if ctx.guild.banner else "None"
After restart, the button won’t work.
I’m trying to recreate a verification join gate so there needs to be a message that stays and should work after restarting of bot.
guys is there something else I can use instead of having a whole file with elif ?
use commands
import discord
from discord.ext import commands
bot = commands.Bot(commands_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f"{bot.user} is ready!")
@bot.command()
async def hello(ctx):
await ctx.reply("Hello World!")
bot.run("token")
I suggest reading the pycord guide. It look like you have found a video tutorial that was outdated and low effort.
?tag guide
I was looking at the quickstart section of the documentation
thanks !
Oh weird that that is in there.
Yeah, its the solution that makes the most sense until you have to scale. Than you use the built in features that handel that a lot better.
Hey guys my slash command options aren't working properly, I don't understand why
When doing my command it don't show the options name is just equal to None no matter what I put after the command
I have from discord.commands import option at the top of my file but I still don't see them
Any ideas ?
@bot.slash_command(name="gay", guild_ids=['764493979587969109'])
@option("name",)
async def gay(
msg: discord.ApplicationContext,
name: str
):```
error:
import discord.abc
ModuleNotFoundError: No module named 'discord.abc'
code:
import discord
from discord import bot
from lxml import html
import random
import requests```
Hi, i'm creating a charbot in Discord, i use Pycord, i have this code: ```py
client = discord.Bot()
@client.event
async def on_ready():
print('Estoy listo!')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hache ayuda'):
await message.channel.send('Para hablar con Hache puedes escribir /hache !')
@client.slash_command(name="hache", description="Habla con Hache!")
async def hache(ctx, text:pycord.Option(str, 'Lo que quieres decir a Hache')):
await ctx.respond(str(sendToHache(str(text))))
client.run(TOKEN)
I have more code, but that's with other modules for ia and that things
console error:
Traceback (most recent call last):
File "main.py", line 60, in <module>
client = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
helpp
anyone?
@commands.command()
async def dump(self, ctx, role:discord.Role):
await ctx.send(role.members)
How do i send role.members members name
I tried role.members.name but it said object list don't have attribute name
which version do you use?
!replit
Read this to find out how you can install Pycord in replit - https://namantech.me/pycord/installation/#replit
How to install the Py-cord library - Pycord Guide
Ty
you have to change some stuff
What like
the version
Would the link provided tell me all this?
can anyone help me with dis pls?
i am using github version of py-cord
Oh wait actualy, if i imported from github (my repo for my bot), will i need to install all this? I already had this version installed + rc1 cos forgot to uninstall the other
we need more code than this...
you have to change it to rc1
So the pip install py-cord==2.0.0rc1
yes
alr
I've installed this, will i also need to install anything else i use (Motor, asyncio,python-dotenv, pymongo ect)
the entire code in script
import discord
from discord import bot
from lxml import html
import random
import requests
bot = discord.Bot(debug_guilds=[898200563018268742])
@bot.event
async def on_ready():
print('on')
bot.run('')
- use commands.Bot
your bot obviously wont run.. without a token (unless you removed for purpose of sharing code)
lastest
rc1?
rc1?
lmao
i removed cuz didnt want the token to leak
@frigid lark
yeah.. change to commands.Bot and lmk
some stuff yes
so i install some of it..?
idk, i installed from replit