#discord-bots
1 messages · Page 101 of 1
@discord.app_commands.checks.has_permissions(administrator)
@tree.command(name="ban", description = "bans the specific user! (Admin) ")
async def ban(ctx, member : discord.Member, reason:str):
await member.ban(reason=reason)
await ctx.response.send_message(f"__**SUCCESSFULLY BANNED {member}! **__")
like that?
yes and rename ctx to interaction to avoid confusion
its not a ctx , its an interaction
administrator = True in the decorator
and also, is this how I make return if member don't the hsve the required permission
return
?
okay so my bot keeps getting rate-limited. what happens if this keeps happening? and i'd appreciate any tips on how to reduce requests 😔
stop trying to ddos discord with your bot 🙄
if you're using replit, getting ratelimited is a typical issue
i did so and it gave me different sets of error
name 'bot' is not defined
name 'bot' is not defined
name 'bot' is not defined
Traceback (most recent call last):
File "c:\Users\Home\Desktop\DingoLingo-master\DingoLingo-master\run.py", line 33, in <module>
@bot.event
NameError: name 'bot' is not defined
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000021EC5606BF0>
He cant kek
You would need a huge botnet and either way cloudflare will still block the attack
well my layer7 bypass is way stronger than anything cloudflare i took down 1.1.1.1 with localhost 🤓
.
please help
im not ignorin ya i just dont use the decorator so im not 100% ;o
you should be able to make an error handler if they are missing perms and return with a message ie "missing perms"
discord.py is not a beginner-friendly library
You should look into the paradigms the library and python use, here's a good list:
cats not saying its impossible, its just going to be reasonably more difficult to jump straight into this instead of learning some core basics first
Cat never said it was impossible, It's the learning curve that is quite difficult as the paradigms used in the library and the principles are quite complex to learn without any base core knowledge
E.g how would you learn about OOP if you dont have a grasp of something like polymorphism, which is an issue i see allot
thanks for explaining even tho I didn't understand some 🥲
hi
dont wanna spam but could u send me the base36 code
nobody understands what noid says half da time, dont worry 😆
Should i be offended?
no it just mean u r too smart for da rest of us
no
how can i create a sync command
?
I only have base64 code sorry
!e
import base64;[print(chr(int(base64.urlsafe_b64decode(s+"="))>>69),end="") for s in 'NDYwNDMwNzMyMDc5NzkwNDA4MzM1MzY=NTk2MTk4NzY4NDYyMjkyNzA4MjI5MTI=Njk2NTQ5MDU2MjIzMjcyNjY5MDIwMTY=NTk2MTk4NzY4NDYyMjkyNzA4MjI5MTI=NjcyOTM3MjIzODA4OTI0NDQyOTUxNjg=MTg4ODk0NjU5MzE0Nzg1ODA4NTQ3ODQ=NjA4MDA0Njg0NjY5NDY2ODIxMjYzMzY=NjU1MjI4MzQ5NDk4MTYzMjczNDAwMzI=NjQ5MzI1MzkxMzk0NTc2MjE2ODgzMjA=NjQ5MzI1MzkxMzk0NTc2MjE2ODgzMjA=NTcyNTg2OTM2MDQ3OTQ0NDgyMTYwNjQ=MTg4ODk0NjU5MzE0Nzg1ODA4NTQ3ODQ=NjA4MDA0Njg0NjY5NDY2ODIxMjYzMzY=NjE5ODEwNjAwODc2NjQwOTM0Mjk3NjA=Njk2NTQ5MDU2MjIzMjcyNjY5MDIwMTY=NTk2MTk4NzY4NDYyMjkyNzA4MjI5MTI=MTg4ODk0NjU5MzE0Nzg1ODA4NTQ3ODQ=NzE0MjU3OTMwNTM0MDMzODM4NTcxNTI=NjU1MjI4MzQ5NDk4MTYzMjczNDAwMzI=NjkwNjQ2MDk4MTE5Njg1NjEyNTAzMDQ=MTg4ODk0NjU5MzE0Nzg1ODA4NTQ3ODQ=NjkwNjQ2MDk4MTE5Njg1NjEyNTAzMDQ=NjYxMTMxMzA3NjAxNzUwMzI5OTE3NDQ='.split("=") if len(s)>0]```
@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.
Never gonna give you up
Uncalled for
That is the point
smh
The ; in import is pointless lol
Yes I'm pretty sure there's on command event and the name is global check I think
He wants to be in one line, so nah
O I didn't know
async def on_command(ctx):
channel = bot.get_channel(log_channel_id)
server = ctx.guild.name
user = ctx.author
command = ctx.command
await channel.send(f'{user} used {command} in {server}')``` ?
exactly
He can always use __import__
😳
!e
print(__import__("base64"))
@primal token :white_check_mark: Your 3.11 eval job has completed with return code 0.
<module 'base64' from '/usr/local/lib/python3.11/base64.py'>
discord.ext.commands.Bot.get_channel can return None making it error prone, why the creation of useless variables over using literals?
hi please can anyone help in my python programming question
How to run multiple bots in a single block of code discord.py?
don't think you can without like threading or similar
generally not worth doing
just run 2 different processes
It is one lined so it's not
Discord just displays as there's a new line but in fact there's no
I didn't know it was 1 liner
Nah I one-line in cringiest way possible
Oh okay
Should I start coding bots later or now? I don't know about tuples and class but know about other data structures.
Async programming isn't also that complicated..
In that case it could've been done better
More cringe?
Depends on what you think async programming is. Just "stick await in frnot of everything" is an incomplete understanding of asyncio, and hence would seem easy. I would say having an intermediate knowledge of asynchronous programming as a general concept, and as python's implementation is quite important as well as intermediate python would greatly help speed along the process
yes
I'm of the opinion that you should work on a project that interests you. If that is a bot, work on a bot. Know, however, that there are a large amount of foundational elements used in bots that will challenge you continually. You can always pair your work with a book like Automate the Boring Stuff to learn the basics as you go.
I also find that people just like to dive into discord bots as their first foray into discord bots, but from what I see a lot, these people end up fighting with the language rather than using it as a tool and working on their bot
Yes
Automate the Boring Stuff is boring
😋
It becomes a mindset of "How do i get python to do what I want it to" instead of "How can I make my bot do what I want it to?"
I saw people saying "JS or PY?"
never read it only read first 3 pages.
Write a discord bot in java I dare you
The answer to that also happens to be the answer to, "Which language are you most comfortable with?"
Yes
Yeah. Bots are cool. They do what you tell them on a platform others can see. It's the right mixture of allure to make them the starting project for many. That's fine, so long as you know the uphill learning challenge is steeper.
Yes, just like IDEs. They ask "Pycharm or Vs code". Go with the one which is comfortable for you...
Since I love a game called blackjack, I am gonna make a bot for it!
I have already made this game months ago but... gonna code it in bot.
You can technically get by without classes for a while, I did my first bot without classes then went back and added them later
I also did it entirely in one file
Would not recommend
hi people !
there's something i'd like to ask but didn't find the proper community to ask:
Someone told me "when you click an image on discord, never click that 'Open Original' because you can get hacked, and I know how to make such images"
I highly suspect that dude to flex and being a bit mythomaniac but you know I said after all it might be true and googled it, and found out there are some tricks possible by adding a VBScript at the end of the text file that could change your windows wallpaper. So I started doubting.
Are images on discord possibily a security breach? :o
you'll eventually learn classes since discord.py ( or actually any general usage python library) is designed that way
The images you see inside of discord are embeds they are embedded into discord from the information of whatever website link was sent. There is always a risk of a website being malicious potentially. Some websites could utilize vulnerabilities to "hack" your computer, etc. Some might just grab your IP address. You're relatively safe by viewing only through discord. Unless you trust the site you should try to avoid opening original
thats not the same for images that people upload manually on discord right
cuz its just some bytes
Bytes are still harmful generally speaking. I would say your safe from an attack via the website directly as uploaded images go through the discord CDN when you view
There is however a chance where there is some kind of vulnerability with the CDN
Unless for whatever reason you'd need to open the original I would suggest just viewing it via discord
This is pretty much do-able with hex editing though, I think I have a non-malicious example
The execution of a snippet of code in a image was patched but it still triggers windows antivirus, as anything that gets sent into discords cache must be read, i'm also not sure if it qualifies as Steganography which i doubt
😭
ohhhh i get what you mean, hang on
in that case you get this from discord right?
is there any way to get hacked without getting this warning message?
oh so it's nothing bad to worry about right?
Can't say for sure. What happens when there is a vulnerability with discord itself?
It just triggers the windows antivirus and the antivirus coroutines the threat so nothing to worry about
alright I get it, but indeed what andy said is right, when you paste an image link it doesn't get into discord's CDN, so you get an embed of the image and that "Open Original" will bring you to the link that got shared which opening it on browser could be malicious for sure. Alrightie !
!e
print(False == 'False')
@paper sluice :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
the false you get from getpuuid['data'][0]['teams']['red']['has_won'] is probably a boolean, you are trying to compare it with a string which is False
result = "Win" if getpuuid['data'][0]['teams']['red']['has_won'] == True else "Lose"
print(result)
That's one way to fix it. But in your case you have another option for not working ^^
anyone have an example of a giveaway bot?
the == True part is not necessary
can someone help me out with the code for adding roles, i forgot it
oh right that's even more concise :D
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
its actual better to check the exact value ( True ) here.
a better approach would be using ... is True instead of ... == True
In some cases omitting the actual check and only seeing if it is truthy will be slower than checking the identity of the thing
@bot.event
async def on_ready():
Channel = bot.get_channel(1027322918570573925)
Text= "TEST"
Moji = await Channel.send(Text)
await Moji.add_reaction('🏃')
@bot.event
async def on_reaction_add(reaction, user):
Channel = bot.get_channel(1027322918570573925)
if reaction.message.channel.id != 1027322918570573925:
return
if reaction.emoji == "🏃":
role = get(user.roles, name="Verified")
await bot.add_roles(user, Verified)
await coro(*args, **kwargs)
File "C:\Users\User\PycharmProjects\PYBOT\main.py", line 88, in on_reaction_add
await bot.add_roles(user, Verified)
AttributeError: 'Bot' object has no attribute 'add_roles'```
please help the below one is the error
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
ye thats what the error is all abt
im trying to code my bot to send a message when i go live on twitch. how can i get my client id and bot token? or do i not need one?
yeah it’s member.add_roles not bot
yeah ive already found it
thank you anyway
#Clear Messages Command
@bot.command(aliases= ['purge','delete'])
@commands.has_permissions(manage_messages=True)
async def clearall(ctx, amount=None):
if amount == None:
await ctx.channel.purge(limit=1000000)
await ctx.send(ctx.message.author.mention + ' `Clear Messages Command` ** has been used succesfully**')
time.wait(1)
await message.delete()
it doesn't delete the msg afterwards
because you don’t have a message object so ur not deleting anything
what should i put
i think ive found it
lemme try
still havent found it
yes you for sure need your bot's token
you can get it from discord developers page
go to ur application -> bot -> ( add bot if already didn't) -> reset and copy the token
you probably won't need the discord bot's client id
can u help me with the give Role command?
do i need any tokens or ids from twitch?
im not very experienced with twitch 's api but probably yes
what library are you going to use?
code/error?
no but i do have an error with this member thingy
async def mir(ctx, role: discord.Role):
members = []
try:
for member in role.members:
members.append(f"\n {member.mention} `{member}`")
except Exception as err:
print(err)
return await ctx.respond('error', ephemeral=True)
e = discord.Embed(title=role.name, description=''.join(members), color=role.color)
await ctx.respond(embed=e, ephemeral=True)
is the code @slate swan
and for twitch integration?
idk, ive never done this before so thats why im trying to look at ways to code it
what are you even trying to do there
to add a role you would be simply using member_object.add_roles(role_object)
how much are you done with the discord bot part?
if you haven't made any progress with nextcord yet, im aware of libs with twitch integration
ill show rq so basically it shows all the members in a role like this
-members @dawn lichen
oops
just use on_presence_update
wouldn't that be totally presence dependent?
like what if they don't use rich presense
yeah that’s the only catch
and if twich api exists, why not use it
also the give Role thingy its suppose to give a role to a player btw.
!pip hikari-kasai :V
prob sure twitch has endpoints for started streaming too
what else could add_roles mean
well that’s what I was gonna say last time I checked they don’t, you have to make a task to check
if they’re streaming
how do u make it slash command?
"A stream goes online"
https://dev.twitch.tv/eventsub/#:~:text=A stream goes online
i have this right now
@commands.Cog.listener()
@tasks.loop(seconds=10)
async def check_For_live_secretsocietyserver(self,ctx):
channel = self.bot.get_channel(1016937526046502973)
API_ENDPOINT = 'https://api.twitch.tv/helix/streams?user_login=secretsocietyserver 10'
Client_ID = "client_id"
botToken = "discordbottoken"
head = {
'client-id': Client_ID,
'authorization': 'Bearer ' + 'discordbottoken'
}
r = requests.get(url=API_ENDPOINT, headers=head, )
w = r.text
if "live" in w:
e = nextcord.Embed(
color=nextcord.Color(0x9146ff),
description=f"Playing (game) for (viewers) viewers\n[Watch Stream]('https://www.twitch.tv/secretsocietyserver')",
timestamp=datetime.datetime.utcnow())
e.set_footer(text="Notification preview")
e.set_author(
name="The Secret Society is now live on Twitch!",
url='https://www.twitch.tv/secretsocietyserver',
icon_url='https://cdn.discordapp.com/attachments/917184938690899971/1009332026148667392/A7049B45-44C4-4E5F-8498-BC11A585F442.jpg')
e.set_image(url="https://images-ext-1.discordapp.net/external/FueXlfSkrjOeYMx92Qe3Y2AaV4G5dk9ijVlNGpF-AgU/https/static-cdn.jtvnw.net/previews-ttv/live_user_overwatchcontenders-1920x1080.jpg")
await channel.send(embed=e)
time.sleep(1800)
else:
print(w)
time.sleep(1)
but the async def function doesnt exist obviously haha
ur better off using presence updates lol.
@Cog.listener()
async def on_presence_update(self, before: disnake.Member, after: disnake.Member):
role = after.guild.get_role(985059814583459851)
channel = after.guild.get_channel(985055579569541141)
for activity in after.activities:
if isinstance(activity, disnake.Streaming):
if role in after.roles:
embed = disnake.Embed(title=activity.name, url=activity.url, description=activity.game)
embed.set_author(name=activity.twitch_name, icon_url=after.avatar.url)
embed.set_thumbnail(url=after.avatar.url)
embed.set_image(url=f"https://static-cdn.jtvnw.net/previews-ttv/live_user_{activity.twitch_name}-500x500.jpg")
await channel.send(content=f"Hey {after.guild.default_role.mention}. {activity.twitch_name} is now streaming @ {activity.url}!", embed=embed)
member_object.add_roles(role_object) how do u use that?
u need a member object lol
i'll try to work with this, thank you so much
does @gloomy cloak_command work with it?
yeah you just need to get a member
mans just pinging everyone 
lmao
ight so embed.set_description works?
@slash_command
member_object.add_roles(role_object)
embed.set_description()```
?? @slate swan
why dont you just try it instead of pinging to ask if something works
u dont even have anything inside to set the description to
because im new to python?
I have a problem
I have installed discord-components and i don's know what's happend
@spark saddle ok but you could easily answer your own question by attempting to run the code and seeing that it results in an error, why are you asking other ppl if something works when they're not the one running the code?
where do i find that?
the error? you run the code and the error pops up in your console
i have one more question how do i mention someones name into the embed?
that import does not exist
i have one more question how do i mention someones name into the embed?
u can tag them but it won’t actually ping them
I try to import buttons
that library isn't really under development anymore
avoid using it
@slate swan and what button library exists now?
discord.py has buttons....
totally not obvious, 50% of users use other libraries now
i can understand
xd
but
i try to make an atractive user interface in my discord bot
how do i make a command that gives a role to a specific user and a specific role? with slash command, options.
I prefer disnake because of their implementation of slash commands, it's quite easier
in dpy its literally just a decorator, you sync then you use commands, not very hard at all
Guys how do you add a role to a specific user, specific role?
ty, can you provide me resources to get started with it
robin how do you add a role to a specific user, specific role?
https://discordpy.readthedocs.io/en/stable/ - the docs for discord.py
anyone?
i really need to learn python
Member.add_roles would be used for this
100%, especially in discord.py and other libs there's a lot of complex/advanced concepts going on and it simply can be hard for new python users to use discord.py
Member.add_roles is that it im trying to make it slash command @flat pier
it would be @gloomy cloak.slash or sum
you have to get the user then use that on that user
yes that would be it, there's no "slash" specific function for that
get user with slash command
ok so how do i make a embed for that it wouldnt completely work to me.
Not really
why does this not work ```weight = input('Weight: ')
switch = input('(L)lbs or (K)g: ')
switch = switch.upper
if switch == 'L':
mathL = weight / 2.205
print(mathL)```
can you explain whats complicated with it
is it like
https://gist.github.com/scragly/095b5278a354d46e86f02d643fc3d64b#required-knowledge someon gave me this it was a good explanation from what i saw
Its abstractions are quite complicated for no reason, like why a tree for app commands?
? its not very hard
its a command tree, same thing differen't wording
Literally makes no sense kek
is it embed.set_title
so it being named tree makes it complicated..?
not to mention its named app_commands in Cogs
embed.set_title(Sign Command)
embed.set_description(User has been signed to a team)
Member.add_roles
is my code
You're missing my whole point, especially on its abstractions where a usage of a tree is used when the app commands are bounded to your bot not to a tree?
Thats kind of like saying, why have a Bot.users when you have Bot.state._users
A tree is just separating the interface into a different area making it easier to navigate
It's more modular as well since you can subclass, etc
Over binding them to the bot like a context command?
They are binded to the bot... Just under a different namespace
But context commands make sense for that as you have a DIFFERENT class for commands, E.g commands.Bot not Client
the tree stuff is a load of horse shit 🤣
Arent they bounded to an instance of a tree which then gets loaded with a method which probably gets parsed?
And what do you think the tree is, bound too..??
Do you magically somehow get state, do you magically somehow get rest?
The app commands would still be bounded to the tree technically?
And therefor it's bound to the client no?
They just probably get internally parsed and setup etc
I'm not sure, dont you setup your app commands with an instance of a tree?
And what do you think you need to make that tree...?
Have you even used discord.py's trees
examples/app_commands/basic.py lines 10 to 20
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
# A CommandTree is a special type that holds all the application command
# state required to make it work. This is a separate class because it
# allows all the extra state to be opt-in.
# Whenever you want to work with application commands, your tree is used
# to store and work with them.
# Note: When using commands.Bot instead of discord.Client, the bot will
# maintain its own tree instead.
self.tree = app_commands.CommandTree(self)```
Which you would use CommandTree.app_command?
Is that no different from client.slash_command?
It's literally just another decorator
Your separating the code which is good
It's like saying, why use Cogs when I can put all the commands in the main file
I didn't design trees myself but I assume a huge point about that is modularity
I don't see how it gets any more complex in the way you put it
It's literally the same access like usual, a decorator
I'm not saying it's not good, I'm just saying its abstractions are quite questionable especially for something that shouldnt be so complex, in discords API it's just app commands bounded to your application I'm not sure why you would make it more complex than that, that just makes more confusion, going to your modular point, cant you just set the app command in a cog in disnake?
you can do the same in dpy?
Never said you cant
We cant forget about pythons zen:
Simple is better than complex.
Complex is better than complicated.
Okay. Why even use an API wrapper then? just do raw requests
HTTP interactions > gateway interactions imo
There is literally no difference other than separating the code. Instead of making the bot's namespace contain all the slash commands related stuff you push it into others. By doing this it gets rid of clutter especially with a lot of sub commands, etc.
If the wrapper decides to make it complicated great. But as a user you are negligibly effected by it
It's literally, just another attribute, just another decorator, and done
That depends on your use-case
You don't even need to have it as an attribute either, you can define it wherever the heck you want, as long as you can pass a Client into it.
Wouldn't say that is all completely true
how? its literally all you do to create a slash command
Eitheir way, this discussion is all based on opinions and personal preference
^
I ment it's not completely true in a sense of abstractions
Its not only another attribute and decorator as ive seen theres more steps to it
in a way they took both implementation approaches as for the base client the command tree is (almost) completely decoupled, but for the commands extension they had to reference the tree several times in the bot/cog to provide a convenient integration of application commands
i.e. if you used Client + CommandTree you always have to reference the tree in order to manage your app commands, but for Bot you get the option to use @app_commands.command() in a cog or the @bot.hybrid_command() decorator which just turns into an app command for you, without the .tree step
yea its simple to me which confused me as to why noid said it was complex after i told someone it isn't very hard to create a slash command
It's simple as you probably already have done it, but to me it's a bit overly complex and complicated and many beginners have issues with them e.g how to sync them and where or when to sync them, i'm not saying disnakes implementation doesnt raise questions either
how to sync and "where" to sync is a thing (or should be a thing) in every lang, no lib should be syncing for you in my opinion
Not sure why given the user a bit more of complication is necessary but sure not wasting a few of the requests to sync your app commands isnt a problem to me, I'm not even sure a lib like disnake even waste those request to sync your commands, either way the limit per day is 200/1d so i wouldnt say that's quite an issue, it can happen as ive seen it happen which it only happened when the user did it manually, which made the user question where to sync the app commands
well, that is because noid is very smart in the aspect of developing. so when noid explains something to someone who doesnt have the same knowledge, it may be looked at as confusing because noid is explaining something with the assumption it can be understood as simply as he/she understands the topic. so yeah it creates confusion. thats why you ask more and more. the more you ask the more you know. dont walk away misunderstanding the topic because one explanation didnt give you the knowledge needed. im sure noid would have been willing to break down the explanation.
so im dumb for saying something is simple to me and complex for them (in a way)? this convo had already been broken down lol
explain argument in fortnite terms
you explicitly stated that you were confused as to why noid said what he said 🤣 nobody called you dumb
it is a copypasta 😆 not meant to offend u
Piece of text which is copied and pasted with minor modifications for humorous purposes
im not offended at all it was just a random response loll
Check in this channel it has been paste d mny times
confused as to why they thought it was complex* there's a large difference there
But with andy instead of noid
ok
but it seems like a valid argument though
it's a common situation with helpers honestly
you were still confused??? that’s the point they were making
they weren't trying to make a point?
it is a copypasta
either way i dont care to argue it anymore
Dont tab the "print(mathL)
Just normally
Anyone who have an example of a paginator with Embeds and components?
I've made one'ish, but the current page is keep messing up.
I have the embeds and views of components like this,
the_list = [[embed, view], [embed, view], [embed, view]]
They get added with a loop,, where each embed and view is different.
How can I add a paginator to that, without also messing up the current page (and total pages) ?
I'm using dpy v2
you could look at my repo, it isn't made using discordpy however even if it's made with disnake the concept is the same
Thank you, but this seems to only be for Embeds though, I already made something similar..
Like this is example what I want.. I made this in older version of dpy (V1) and another old 3rd party
and when going to next page, the components changes too
from what I can see it is easily implementable even with the example I gave you though I can't think of an actual implementation if I can't work on it
maybe I'll try to do a paginator with multy view
I'm probably looking on it in a wrong way, because right now, when I switch pages the current page index button gets messed up
how are you unpacking the lists of embed and view?
you're using static indexes?
if you want you can share the code
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Not on my pc now, but, well, first I made I added all the components to a list with the embeds..
So they go like this:
[[embed, [btn1, btn2, btn3, btn4, btn5], [embed, [btn6, btn7...]... ]
That was to get the total pages.
I then added the 5 buttons of each elements to a View, which i then replaced them with,
so it became like this, [[embed, view], [embed, view]...]
Sorry, I'm typing from my phone atm
For each element i added there was a a custom variable which was the current page.
That's where it gets messed.
Since they go +1 or - 1 everytime I go previous or next page
you should treat the sublist as the same way you treat it when there are only embeds and unpack two variables from it
first get the sublist with the page index
page_index = 1
components = [[...], ...]
msg_component = components[page_index]
embed, msg_view = msg_component
where msg_component is the sublist, e.g [embed, view]
note that that's only an example and it won't work if you copy paste it, I've made it just to let you understand
I haven't test this logic but should work well
I'm having a brain fart now. Need some rest
okie, you can freely contact me if you need further information
I want to send a log embed for when a member gets timed out. How do I do that?
#Clear Messages Command
@bot.command(aliases= ['purge','delete'])
@commands.has_permissions(manage_messages=True)
async def clearall(ctx, amount=None):
if amount == None:
await ctx.channel.purge(limit=1000000)
await ctx.send(ctx.message.author.mention + ' `Clear Messages Command` ** has been used succesfully**')
time.wait(1)
msg = message.content.lower()
if ".clearall" in msg:
await message.delete()```
it doesn't delete the message
where is message coming from?
and you clearall is already a command
use purge to delete large amounts
Use on_member_update event
!d discord.on_member_update
discord.on_member_update(before, after)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") updates their profile.
This is called when one or more of the following things change...
That channel is closed
I know, but it'll help you catch up
Ok so ur question is how to get duration of time out?
You will need to get datetime of when the timeout was issued
Through audit log or storing it urself
Is it straight forward via the audit log?
U have to go through audit log and find the correct entry
Alright. I'll do it later
You could use on_member_update and check if the member got timed out and save it somewhere instead of looping through the audit log entries, but you do you
I was thinking more trying my luck with Discord themselves and asking for an event that bots can access for the duration (ie, an output like "1 minute, 10 minutes, etc."
on_member_update provides you the member object that has those fields
!d discord.Member.timed_out_until
An aware datetime object that specifies the date and time in UTC that the member’s time out will expire. This will be set to None if the user is not timed out.
New in version 2.0.
You could compare the timed_out_until with the current time that the event was triggered
lucas owo
okay so you need to await load_extensions now
that code is outdated
for the most of part yes
yes exactly
yep, but inside an asyncio.run()
yes
both bot.run and start works
you'll be awaiting start tho
hm is the cog loaded
bot.run isn't a coroutine, so don't await it smh
!e x += 1
@upbeat gust :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'x' is not defined
no worries
can someone help? is my ban command good?
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'**SUCCESSFULLY BANNED** __**{member}**__!')
@ban.error
async def ban_error(ctx, error: client_commands.AppCommandError):
if isinstance(error, client_commands.MissingRole):
await ctx.reply(f"You dont have that perms.")
you forgot await in the ctx.send
oh yes
hey everyone, was wondering if anyones attempted to make a bot which dms the user the moment they join your server?? im wanting to make one so users have a FAQ about the server plus a cool cat gif at the bottom ahah
you can just listen for the on_member_join event?
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
thanks, so is that how I make if the member doesn't have the permission and it replies with "you don't have perms "
??
you forgot the @ban.error decorator
there is one
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
like this?
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'**SUCCESSFULLY BANNED** __**{member}**__!')
@ban.error
async def ban_error(ctx, error: client_commands.AppCommandError):
if isinstance(error, client_commands.MissingRole):
await ctx.reply(f"You dont have that perms.")
or this?
@client.command()
async def ban(ctx, member : discord.Member, *, reason=None):
await member.ban(reason=reason)
await ctx.send(f'**SUCCESSFULLY BANNED** __**{member}**__!')
@ban.error
async def ban_error(ctx, error: on_commands.error):
if isinstance(error, client_commands.MissingRole):
await ctx.reply(f"You dont have that perms.")
you mean the raw api?
Yeap
damn okay
Does anyone know some sort of Discord's voice gateway libraries? To securely join voice chats through my own website xd
Hmm, but can you receive data from voice channels? https://discord.com/developers/docs/topics/voice-connections
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
yes
Welp I need to do it through raw api, so I'm going to need to find out, how they are doing it
Bruh it's not actually supported
Oh okay, Thanks!
Mhm
idk where this would fit so im sending it here randomly but where can i find commands and stuff for the kahoot api
lol
what's up brother
what is discord.utils.find?
!d discord.utils.find its like get but can search thru a function as well
discord.utils.find(predicate, iterable, /)```
A helper to return the first element found in the sequence that meets the predicate. For example:
```py
member = discord.utils.find(lambda m: m.name == 'Mighty', channel.guild.members)
``` would find the first [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") whose name is ‘Mighty’ and return it. If an entry is not found, then `None` is returned.
This is different from [`filter()`](https://docs.python.org/3/library/functions.html#filter "(in Python v3.10)") due to the fact it stops the moment it finds a valid entry.
Changed in version 2.0: Both parameters are now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s.
.get works with with a particular attribute, .find works with a user defined function
Not in the channel meant for discord bots 😆
But u should check online, if you can't find it then you'll have to read da source code
alr
i didn’t know where to put it lol
im pretty sure the thing is js so idk how to translate to python lol
lmao it was originally written in js
kahoot.py is just an alter for that
https://github.com/DarthOCE/kahoot.py/blob/main/Documentation.md here's the docs
but well, it's better if you make your own scraper since that lib has a lot of issues and is severely undocumented
valorant = app_commands.Group(name="valorant", description="Valorant Commands")
#@app_commands.command(description='Valorant Commands')
#async def valorant(self, ctx):
# await ctx.send("WIP val commands")
@valorant.command(description='Log in with your Riot acoount')
#@valorant.describe(username='Input username', password='Input password')
# @dynamic_cooldown(cooldown_5s)
async def login(self, interaction: Interaction, username: str, password: str) -> None:
response = ResponseLanguage(interaction.command.name, interaction.locale)
i am trying to make sub commands for app_commands but now they arent appearing when i sync the commands and try to type them out am i mission something?
can you print while calling the sync method and see if the command names/group appear there? print(await sync())
and you'll have to use @app_commands.describe
Yup i can
cool
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\client.py", line 502, in _run_event
await coro(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\bot.py", line 200, in on_application_command_error
raise error
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\application_command.py", line 863, in invoke_callback_with_hooks
await self(interaction, *args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\cooldowns\cooldown.py", line 93, in inner
result = await func(*args, **kwargs)
File "c:\Discord\Maja Projekt\MajaSystem_Test\modules\information\cog.py", line 200, in userinfo
await interaction.edit_original_message(embed=userinfo, view=view)
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\interactions.py", line 451, in edit_original_message
params = handle_message_parameters(
File "C:\Users\domin\AppData\Local\Programs\Python\Python310\lib\site-packages\nextcord\webhook\async_.py", line 537, in handle_message_parameters
payload["components"] = view.to_components()
AttributeError: 'coroutine' object has no attribute 'to_components'```
well i tried to show you but uh
discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)
you got ratelimited, sadly
@nextcord.slash_command(name="userinfo", description="Shows you a user info of a user!")
@custom_check.has_moderation_and_admin_role_interaction()
@custom_check.If_User_on_UserBlacklist_Slash()
@cooldowns.cooldown(1, 25, bucket=cooldowns.SlashBucket.guild)
async def userinfo(self, interaction: nextcord.Interaction,
_member: nextcord.Member = SlashOption(name="member", description="Please select a member", required=False)):
member = _member or interaction.user
await interaction.response.send_message(embed=wait)
@nextcord.ui.button(label="Show all Roles", style=nextcord.ButtonStyle.blurple)
async def show_member_roles(interaction: nextcord.Interaction):
all_roles = await interaction.user.get_roles(interaction.user)
embed_roles = nextcord.Embed(description=all_roles)
await interaction.response.send_message(embed=embed_roles)
view = show_member_roles(interaction)
de = pytz.timezone('Europe/Berlin')
await self.universal_log_embed_slash(interaction, _member=_member)
await interaction.edit_original_message(embed=userinfo, view=view)```
yo anyone can help me with a slash command add role to a specific user and a specific team?
just get the member object and use the add_roles method on the member
async def mir(ctx, role: discord.Role):
members = []
try:
for member in role.members:
members.append(f"\n {member.mention} `{member}`")
except Exception as err:
print(err)
return await ctx.respond('error', ephemeral=True)
e = discord.Embed(title=role.name, description=''.join(members), color=role.color)
await ctx.respond(embed=e, ephemeral=True)
py-cord?
that's seriously invalid
Do I need to wait till exactly midnight to try again or?
then what do i do?
right, you'll have to wait till the midnight of the region where the servers are located
see the second pin of the channel to learn how slash commands are created
which one
Can someone help (nextcord)
#channel?
this channel 💀
OH
Can someone help me fix this code?
async def mir(ctx, role: discord.Role):
members = []
try:
for member in role.members:
members.append(f"\n {member.mention} `{member}`")
except Exception as err:
print(err)
return await ctx.respond('error', ephemeral=True)
e = discord.Embed(title=role.name, description=''.join(members), color=role.color)
await ctx.respond(embed=e, ephemeral=True)
doesnt need to be slash
ctx.respond is still invalid
how do i fix that?
That has to be pycord
oh its pycord?
...
...you don't know the library your own code uses?
imma take my leave lmao
i didnt create this code
someone gave it to me
I come and you leave immediately i see how it is
And what if they put something malicious in it?
ily dw
i didnt download it
How are you planning on running it?a
And malicious things don't necessarily need to be downloaded
So i hope you trust your source
oh
import discord
from discord.ext import commands
client - commands.Bot(command_prefix - '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
client.run(token)
can someone help?
I made this by myself
Guys i want to make a python library that can help people make discord bots some easily
Can anyone suggest me any idea?
At what you need help?
this command i made
import discord
from discord.ext import commands
client - commands.Bot(command_prefix - '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
client.run(token)
thats the command @robust fulcrum
Whats wrong in it?
i dont have a <module> thats called "discord" and idk how to fix that.
Just do pip install discord.py
You need to install discord.py for that
Any know any good videos to learn discord.py I have made discord bots I’m just new to the new version
Don't change anything
Just install discord.py using pip
You can just read the migration guiide
Guys i want to make a python library that can help people make discord bots some easily
Can anyone suggest me any idea?
Pls anyone suggest me
Make discord bots easily how
You want to create your own wrapper?
assignment is done using =, not -
package
!pypi <package>
Can also use: pack, package, pip
Provide information about a specific package from PyPI.
How can I make a select menu option for every one of my cogs using a for loop?
Few inches taller, and you bro?
how do i use an if custom_id from a button = something
I don't understand your question
so in a button i used a custom_id thing
how do i use an " if " with it like if the custom_id of the button is for example 1 it will print smth ?
if the button id is smth else it will print smth else
? you there
!d discord.ui.Button.custom_id - Just use it to compare it to something you said
property custom_id```
The ID of the button that gets received during an interaction.
If this button is for a URL, it does not have a custom ID.
you dont understand my question
ill make an example
so i have a button with label="1" and custom_id="1" and another button with label="2" and custom_id="2"
like a button_callback but just with 2 buttons in 1 callback
i found it but another question
how do i place the thing in the image easier ? like in 1 thing instead of naming it like that for all the buttons
You could subclass the view and put your desired buttons and callbacks in it
how ?
examples/views/counter.py lines 21 to 28
class Counter(discord.ui.View):
# Define the actual button
# When pressed, this increments the number displayed until it hits 5.
# When it hits 5, the counter button is disabled and it turns green.
# note: The name of the function does not matter to the library
@discord.ui.button(label='0', style=discord.ButtonStyle.red)
async def count(self, interaction: discord.Interaction, button: discord.ui.Button):```
what do i have to see here ?
Can anyone help me out with a basic problem with discord bot?
bot.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2022-10-06 21:27:10 INFO discord.client logging in using static token
2022-10-06 21:27:12 INFO discord.gateway Shard ID None has connected to Gateway.```
i am getting this error
await bot.load_extension also await only inside async function
can i dm you
Hey @hidden hazel!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
How do I add an avatar image to a webhook.
await interaction.channel.create_webhook(name="Roles", avatar=)
Idk what to put after the avatar= part
import discord
from discord.ext import commands, tasks
from discord.ext.commands import bot
class event(commands.Cog):
def __init__(self, client) -> None:
super().__init__()
self.client = client
@commands.command()
async def hello(self, ctx):
await ctx.send(f'Hello')
async def setup(client: commands.Bot):
await client.add_cog(event(client))
why my code dont work?
who can help me please
@primal token :x: Your 3.11 eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: list indices must be integers or slices, not str; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: list indices must be integers or slices, not str
You can only index elements from a list with their position
!d discord.TextChannel.create_webhook - The avatar parameter will take data of an image as bytes, and it's optional
await create_webhook(*, name, avatar=None, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a webhook for this channel.
You must have [`manage_webhooks`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_webhooks "discord.Permissions.manage_webhooks") to do this.
Changed in version 1.1: Added the `reason` keyword-only parameter.
kk
hi
lol
bot perms !!
overwrites = {
guild.me : discord.PermissionOverwrite(manage_channels = True , view_channel= True , manage_permissions = True) ,
guild.default_role: discord.PermissionOverwrite(connect=False) ,
discord.Object(ctx.author.id): discord.PermissionOverwrite(connect=True)
}
PVC = await guild.create_voice_channel(f"{ctx.author.name}'s Pvc" , position = 0 , category = discord.Object(pvc_category) , overwrites=overwrites)
use correctly Hybrid command raised an error: Command 'pvc' raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
error
TextInput(
style=TextStyleType.SHORT,
label="Enter The Code",
value="Enter The Code That You Have Been Given!",
custom_id="text-input-1"
)
textstyletype is not there or something
i think it is with your json file
its TextInputStyle
now i get a error on the TextInput(
code = discord.ui.TextInput(label="Enter The Code")
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(code, ephemeral=True)``` so i got my modal and when i enter everything it is all working but i can't seem to get the entered data please help
hey, does anyone know how i can make a specific button for each item in a dict
?
you can get the result with self.code.value
!d discord.ui.TextInput.value
property value```
The value of the text input.
import token
from discord.ext import commands
client = commands.Bot(command_prefix - '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases=['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
client.run(token)
2 errors its discord.ext and command_prefix
Sure. Just subclass discord.ui.Button and use add_item in your discord.ui.View instance
You have a typo, it should be = instead of -
in where?
client = commands.Bot(command_prefix - '-')
here
To be able to import from discord.ext you need to import discord first
I can't tell what those errors are but I'm guessing it's probably that you don't have discord.py installed
Also are you following a tutorial? That code seems familiar
yeah but i coded it by myself like I wrote it
Great. Just as a note of advice though I'd either be very careful about following those tutorials or just not use them as a resource altogether
oh
where is my discord.py suppose to be im pretty new to this is it a extension or do i make a folder and put it inside of the folder?
@sick birch
https://discordpy.readthedocs.io/en/stable/intro.html see here for an installation guide
Collecting discord.py
Downloading discord.py-2.0.1-py3-none-any.whl (1.1 MB)
---------------------------------------- 1.1/1.1 MB 16.6 MB/s eta 0:00:00
Collecting aiohttp<4,>=3.7.4
Downloading aiohttp-3.8.3-cp310-cp310-win_amd64.whl (319 kB)
---------------------------------------- 319.7/319.7 kB 20.6 MB/s eta 0:00:00
Collecting charset-normalizer<3.0,>=2.0
Downloading charset_normalizer-2.1.1-py3-none-any.whl (39 kB)
Collecting yarl<2.0,>=1.0
Downloading yarl-1.8.1-cp310-cp310-win_amd64.whl (55 kB)
---------------------------------------- 55.9/55.9 kB ? eta 0:00:00
Collecting frozenlist>=1.1.1
Downloading frozenlist-1.3.1-cp310-cp310-win_amd64.whl (33 kB)
Collecting aiosignal>=1.1.2
Downloading aiosignal-1.2.0-py3-none-any.whl (8.2 kB)
Collecting async-timeout<5.0,>=4.0.0a3
Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)
Collecting attrs>=17.3.0
Downloading attrs-22.1.0-py2.py3-none-any.whl (58 kB)
---------------------------------------- 58.8/58.8 kB ? eta 0:00:00
Collecting multidict<7.0,>=4.5
Downloading multidict-6.0.2-cp310-cp310-win_amd64.whl (27 kB)
Collecting idna>=2.0
Downloading idna-3.4-py3-none-any.whl (61 kB)
---------------------------------------- 61.5/61.5 kB ? eta 0:00:00
Installing collected packages: multidict, idna, frozenlist, charset-normalizer, attrs, async-timeout, yarl, aiosignal, aiohttp, discord.py
WARNING: The script normalizer.exe is installed in 'C:\Users\jorda\AppData\Local\Programs\Python\Python310\Scripts' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed aiohttp-3.8.3 aiosignal-1.2.0 async-timeout-4.0.2 attrs
thats what it says
@sick birch
ok now what
Run your script and it should work
Can I see the error?
so like code2 = self.code.value?
Did you try running the script?
sure
you can also use it outside of the modal cause its an attribute of the modal instance
ya no
I think you're looking at the wrong tab
Select the "terminal" tab at the bottom, then run it from there
what?
self is not defined
I believe the output is for VSCode-related things like extensions or any language servers
where
Should be at the bottom where you see "output", "debug console"
just hit terminal, then run your file again
its stil lthe same
What's it say now?
are you getting it from outside the on_submit function?
if yes then it would be nameofmodalvariable.code.value
Yes, but can I see what it says?
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.
Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows
PS C:\Users\jorda\Documents> & 'C:\Users\jorda\AppData\Local\Programs\Python\Python310\python.exe' 'c:\Users\jorda.vscode\extensions\ms-python.python-2022.17.12791010\pythonFiles\lib\python\debugpy\adapter/../..\debugpy\launcher' '58588' '--' 'c:\Users\jorda\Documents\import discord.py'
Traceback (most recent call last):
File "C:\Users\jorda\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in
Could you send a screenshot of your screen?
Hey @spark saddle!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
oh now its working thank you
You need to press the "save" button in the top right hand corner, then send the link
there you go
there
Now we're getting somewhere. You're missing intents
oh
You can pass in default intents like so
intents = discord.Intents.default()
bot = commands.Bot(..., intents=intents)
You'll probably also need message content intents
where do i put that
So:
You can pass in default intents like so
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
make sure you enable it in your discord developer portal as well
Create the default intents instance right above your bot/client instance declaration
How does your code look like now?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
client = commands.Bot(command_prefix = '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases=['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
client.run(token)
You don't need to instantiate a completely new bot instance
bot = commands.Bot(..., intents=intents)
I only included this to hint at where the new piece of code should go, but you already have it
You only need these two lines
intents = discord.Intents.default()
intents.message_content = True
Oh and you'll also want to pass it into your bot instance, of course
What does it require to build a chatbot along with ML?
still doesnt work
How does the code look now?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix = '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases=['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
client.run(token)
You haven't passed your intents instance into your bot constructor
Right now it's just kind of sitting there, not doing anything
oh
TypeError: init() missing 1 required keyword-only argument: 'intents'
it shows that now @sick birch
btw im using replit now
simpler
You're sure you're passing in intents properly?
How about in the code?
huh
I disagree, but if it works for now I suppose it's alright. Though I'd still stay away from it
intents = discord.Intents.default()
intents.message_content = True
Yes but this in itself does nothing
You need to pass it into your bot constructor
where do i go for that?
see this
How does the code look like?
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(..., intents=intents)
client = commands.Bot(command_prefix = '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases=['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
client.run(token)
how can i get the user id of the person who pressed a specific button?
interaction.user.id
#discord-bots message see here
remove the client = commands.bot .... and where you have bot = replace the 3 points for the command prefix
thanks
how do i make a prefix for the command?
It's just your command_prefix = "-", no?
How does it not work?
thats the error
What is?
how can i add a user to a private channel?
command_prefix = "-"
How is that an error?
NVM
If by "private channel" you mean a channel with restricted permissions that only certain users can see, then perhaps this https://discordpy.readthedocs.io/en/stable/api.html?highlight=discord textchannel#discord.TextChannel.set_permissions
then it doesn't work for me
I'm not sure what the error actually is. What you're sending is code, which is different from the error
if row[0] == code2:
await interaction.response.send_message("Your code is correct, adding you to the channel!", ephemeral=True)
channel = bot.get_channel(1027715488878436432)
await channel.set_permissions(interaction.user, read_message_history = True, send_messages=True, add_reactions = True)```
I can't help fix a problem if I don't know what's wrong
the user i want to add like i did in channel.set_permission is not added to the channel
and i get no error in terminal
Traceback (most recent call last):
File "main.py", line 7, in <module>
client = commands.Bot(command_prefix = '-')
TypeError: init() missing 1 required keyword-only argument: 'intents'
thats the error
@sick birch
remove intents.default() for intents.all()
That won't change anything
Like I've said before, you need to pass in intents to your constructor otherwise it won't do anything
how do i do that?
See this. Don't copy paste it, it isn't meant to be a plug and play solution. It's only a structure. It tells you where to put things
where do i go to pass my intents to my constructor
Your constructor is commands.Bot(...), yes?
That's what you have in your code
You would add your intents to the end, so it looks like commands.Bot(..., intents=intents)
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
commands.Bot(..., intents=intents)
commands.Bot(command_prefix = '-')
@client.event
async def on_ready():
print('Drome is Online')
@client.command(aliases=['p'])
async def ping(ctx):
await ctx.send('Pong!')
@client.command(aliases=['8ball', '8b'])
async def _8ball(ctx, *, question):
responses = [
'Hell no.',
'Prolly not.',
'Idk bro.',
'Prolly.',
'Hell yeah my dude.',
'It is certain.',
'It is decidedly so.',
'Without a Doubt.',
'Yes - Definitaly.',
'You may rely on it.',
'As i see it, Yes.',
'Most Likely.',
'Outlook Good.',
'Yes!',
'No!',
'Signs a point to Yes!',
'Reply Hazy, Try again.',
'IDK but you should join my bot server ngl',
'Better not tell you know.',
'Cannot predict now.',
'Concentrate and ask again.',
"Don't Count on it.",
'My reply is No.',
'My sources say No.',
'Outlook not so good.',
'Very Doubtful']
await ctx.send(f' :8ball: Question: (question)\n:8ball: Answer: (random.choice(responses))')
commands.Bot(..., intents=intents)
client.run(token)
oops
i removed it now
you're just instantiating commands.Bot, you're not assigning the object to a variable. f-strings are with curly brackets: {}, not parenthesis
Anyone who have an example of a paginator with Embeds and components?
I've made one'ish, but the current page is keep messing up.
I have the embeds and views of components like this,
the_list = [[embed, view], [embed, view], [embed, view]]
They get added with a loop,, where each embed and view is different.
How can I add a paginator to that, without also messing up the current page (and total pages) ?
I'm using dpy v2
A screenshot example I made in V1 with another old 3rd party
guys how do i download discord.ext
You don't
It's included in the discord module
The term library should be used, as its a folder with modules and subfolders, over using module which refers to a file that contains src code
it gets the point across
I'd use the right term if that was their question, but these are 2 unrelated questions
Never said it didn't, but it's not exactly correct, talking about questions, isnt it better giving the correct view/point correctly with the correct terminology over raising questions or causing more trouble to a user, helpers should give great help over help that may cause further questions because of the wrong usage of terms, no? Not saying your help isnt good, but of course it should be as exact as possible
https://docs.python.org/3/tutorial/modules.html
A module is a file containing Python definitions and statements.
uhm, so how do I take a variable from outer class?
I basically have a View class inside a Cog,
So example
class the_cog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
self.a_list = []
class the_view(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
print(len(the_cog(None).a_list))
@commands.command(name="nice_command")
async def nice_command(self, ctx: commands.Context):
self.a_list.append("Anything")
view = the_cog.the_view()
async def setup(bot):
await bot.add_cog(the_cog(bot))
Like example this would still print 0 instead of Anything in print(len(the_cog(None).a_list)) under the_view
the list wont have a length of 1 since the nice_command function hasnt been called yet
over raising questions or causing more trouble to a user
You're right, in this case it really doesn't matter. It probably seems to people that modules and libraries are interchangeable terms, I could've used either. Module came to my head first, so I used it. In the vast majority of cases though, trying too hard to be terminologically (i don't know if that's a word) can and will raise more questions, so I try to use the most laymen terms I can so we can solve the question on hand instead of going on tangents to try and explain some terminology I used. In this case you're correct though, thanks for pointing it out
The view class is called, when I trigger nice_command
Well, the terms arent interchangeable so giving a word or/and term another definition thats not the one in python document is incorrect and contradictory, its better to have the correct definition of some terms or concepts over spreading false information?
you made an instance of the_cog which should be named TheCog to follow pep8, which then you tried to print the length of the list which of course would be 0 and that instance youre creating isnt even being registered
The logic of the code isnt correct
Im wanting to make the bot send an embed instead of message ?? any ideas how i could do that ??
import discord
import asyncio
import sys
import random
import re
import os
client=discord.Client()
@client.event
async def on_ready():
print('Welcome message bot Logged in')
print(client.user.name)
print(client.user.id)
print('-----')
newUserMessage = """your message
"""
@client.event
async def on_member_join(member):
await client.send_message(member, newUserMessage)
client.run('token')
I don't recall send_message being a method of discord.Client?
i mean im currently learning python as a whole and this was copied off of a github as i needed the bot straight away, just tryna figure out that issues with it ahha
Oh, I see. Yeah that's not a very good idea. Discord bots have a bit of a pre-requisite in that you need to know a decent bit of python before starting
Wherever you got this code from, it's either A) written by someone who doesn't know what they're doing or B) just really, really outdated
I mean a library that helps in writting difficult code easily
I am not able to tell you properly.
You mean like.. github copilot?
yeah i started learning cause the dev i paid to make 4-5 bots for my server ended up messing up all the sources and not coding them properly so i had to go through and painfully learn how to fix the errors lol
Ah you not able to understand what i mean
I want to make library like discord.py superutilis
That's common. I'd never pay anyone on Discord for anything really, unless it's a 100% trusted and vetted source. The discord bot space is kind of weird in that a lot of people don't really know best practices or how to create a bot or its infrastructure properly
Sure you could, but you'd still be writing the difficult code, just abstracted away into a utilities file
I am not able to understand what would the difficult code
Like i can make a comamnd which writes discord.py boilerplate?
Oh, as for the boilerplate people will usually have a github repo with the necessities. We actually have our own called python-discord/botcore
Whenever we need to make a new bot we always start with the botcore as it has a lot of the boilerplate
yeah like i truly have all day everyday to learn coding and spend like 6-8 hours daily learning but the moment I look at tutorials i get extremely overwhelmed
Good, don't look at tutorials
Most of them are outdated by now and even when they weren't, they weren't very good to begin with
yeah ill take that advice like gold and butter haha what would be the best place to learn?? read over the discord.py doc or slowly make small simple bots and slowly go from their learning practically ?
Can you suggest anything that i can make?
!projects if this is what you mean?
Kindling Projects
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
I wouldn't recommend jumping head first into discord bots, best to take it slow and learn Python first
!resources as for resources, see here VVV
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Robin you're using the command incorrectly
which one
didn't even know that was a thing tbh
doesn't seem to do anything though
probably accounted for this 💀
okay ill stick with this resource pack then, before i go and start reading this, does this teach python as a whole or just discord python ?? i know both are the same aha
What's discord python?
The resources listed there are quite varied. I'm not sure if there are any discord bot python related guides in there, if so, all the better. But you should focus on learning python as an overall
yeah i will and thank you for taking the time to explain things properly to me 🙂
no worries
Basically I'm trying to make paginator with embeds and components,
I'm having a hard time not messing up the Current page and/or total pages
Now, I have the total pages working on the index, but the current page in the index button isn't working
I do change it init and I also see self.cog.index is changing.. but the Index button isnt updating
I also try to change it with the interaction of the button before editing the message, but still nothing
my bot can't read messages
try to use unicode for emoji
are you gonna open source this O.O i love to see how your doing that
me too
insane what discord bots can do aye ahaha hopefully he can slide us the sauce for it haha
I've had it for a while, and still using Discord.py V1, since I haven't figured how to build it properly on V2 yet
you are right but my bot can't even read messages
Doesn't make any difference
please FOSS it
try to update discord.py
would it be respect if i asked for the github for this project ? if not its algoods 🙂
It's not public
I have latest version
oh okay sorry
sometimes latest version has bugs
It's not a bug
I'm not getting any errors
then what is your problem
Current page button label is not changing
where is source code
So everytime I go next page it the label of IndexButton stays the same for some reasons
can you use if to check button state
What do you mean
Finally after 3 days of trying to get it to work properly, I finally managed
how you did it
Going to publish a smaller version later
how can i get a role by id to set channel perms.. ive tried same methods as adding role but its not returning a role object for the channel.set_perms
^ in a cmd so i have ctx
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
Changed in version 2.0: `role_id` parameter is now positional-only.
How can I pass a dictionary as the variables for a sqlite query?
await cur.execute("INSERT INTO playerprofile VALUES (:bmid,:steamid,:playername,:rusthours,:aimtrain,:steamurl,:avatar,:relatedplayers,:updatedat,:names,:kills_week,:kills_day,:deaths_day,:deaths_week,:gamebanned)",({playerinfo}))
where playerinfo is a dictionary
lol
query_data = {
...
}
await cur.execute(..., **query_data)
i suppose i owe you some help eh
I don't see what's wrong with putting the logic in the view class
Hey @hidden hazel!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Are all the buttons the same?
What information is different between each button?
Do they need to be dynamic?
E.g, will all the information about the buttons be known before runtime?
Okay.. so this might be an easier alternative:
class MyView(discord.ui.View):
def __init__(self):
super().__init__(...) # regular view constructor arguments
@discord.ui.button(label="Notifications", ...)
async def notifs_callback(self, button: discord.ui.Button, interaction: discord.Interaction) -> None:
...
@discord.ui.button(label="Nickname", ...)
async def nickname_callback(self, button: discord.ui.Button, interaction: discord.Interaction) -> None:
...
Because as it stands, I don't see any use for a button subclass
Sure can
class MyView(discord.ui.View):
def __init__(self):
super().__init__(...) # regular view constructor arguments
@discord.ui.select(...)
async def select_callback(self, select: discord.ui.Select, interaction: discord.Interaction) -> None:
...
It's practically the same thing
that's not really necessary in your case
but it's there if you'd like
Ah, my bad. I had a feeling it was the other way around
You forget things like that after a while, my apologies
gv
aahh
raise ValueError("unconverted data remains: %s" % ValueError: unconverted data remains: .794388 ;-;
lastupdate = datetime.datetime.strptime( fromdb['updatedat'], '%Y-%m-%d %H:%M:%S')
perhaps fromdb['updatedat'] is in a weird format?
2022-10-07 14:03:44.794388
it's stored as a string for whatever reason
and I need to convert it to a datetime so I can compare it
fuck it. I dont need the h/m/s anyway
just remove them 😄
You'll need to chop off that last decimal bit or store it in such a way that it doesn't appear
it's fiiiiine
preferably the latter which targets the source of the issue
weekago = datetime.datetime.now(
timezone.utc) - datetime.timedelta(hours=168)
weekago = str(weekago)
weekago = weekago.split(" ")
weekago = weekago[0]
weekago = datetime.datetime.strptime(weekago, '%Y-%m-%d')
db = DataBase()
fromdb = await db.get_playerinfo(bmid=bmid)
if fromdb:
lastupdate = fromdb['updatedat']
lastupdate = lastupdate.split(" ")
lastupdate = lastupdate[0]
lastupdate = datetime.datetime.strptime(
lastupdate, '%Y-%m-%d')
if lastupdate < weekago:
print('Updated a week ago :/')
return
else:
print("NOT IN DB!!")
Solution!
Hmm. I would use strftime to store it in the db in a way you can predict
And use the same argument in strptime
It's consistent and would work because you're storing it and retrieving it in the same manner
dt_format = '%Y-%m-%d'
weekago = ...
weekago_str = weekago.strftime(dt_format)
# store `weekago_str` to
And retrieving:
lastupdate = fromdb['updatedat']
datetime.datetime.strptime(lastupdate, dt_format)
!e
import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
@shrewd apex :white_check_mark: Your 3.11 eval job has completed with return code 0.
2022-10-07 03:49
ah
How Can i add owners to my jishaku command?
do they have low level?
Wdym low level in this case
components. rather than using a view, disnake has something called low level. where you assign the components with the message then use a listener for when the components are interacted with.
discord.py uses callbacks instead of events
Something similar to the components thing can be done though
disnake does too they just give u the option to use low level or views.
view = View()
view.add_item(myButton)
.send(view=view)```
Close enough
also benefits to low level as well compared to views
@bot.command()
async def send_button(ctx: commands.Context):
await ctx.send(
"Here's a button!",
components=disnake.ui.Button(label="Click me!", custom_id="cool_button"),
)
@bot.listen("on_button_click")
async def cool_button_listener(inter: disnake.MessageInteraction):
if inter.component.custom_id != "cool_button":
return
await inter.response.send_message("You clicked the cool button!")
beautiful
No thanks
Interesting
memory management in discord.py in general is not so good, you have no control over it
the same applies for forks
discord.py has on_interaction event as well. you just gotta check that the interaction was a button, that's exactly same as on_button_click
disnake/state.py lines 953 to 954
if interaction.data.component_type is ComponentType.button:
self.dispatch("button_click", interaction)```
How may I send messages at a specific time? Let's say I wanna send a message at 2 pm.
I don't wanna use. ```py
await asyncio.sleep(8000)
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
You can pass datetime object to the time parameter
Thanks!
can someone help..
Returns True if a user can send messages from all or specific text channels.
its send_messages
ohh i forgot to add s
why is it indented inside analysers
Tell me then what i do?
Aapke profile mai achha mantra hai
@slate swan
remove the space before that field
why are you using that toml file anyways?
😳
yaml all the way 

What is ctx.guild.22341534161346_role?
Okay but why is it an attribute of guild?
server?
do i need to make it
ctx.channel(the id role), send_messages = True)
?
orr
no?
???
U cant put random shit together and expect it to work xd
Do you understand what function is
no?
Ok, do you know anything about python
kinda
You supposed to know python fundamentals before making discord bot
Like functions, classes, data structures
is it like this then?
ctx.channel.set_permissions(ctx.guild.channel.1023331692515164222_role, send_messages = True)
or
ctx.channel.set_permissions(ctx.guildchannel.1023331692515164222_role, send_messages = True)
what the fuck
?
You really should learn python before attempting to do whatever you're trying to do
I hope you know that putting random symbols and words together won't magically make your code work...
collab = await collab_category.create_text_channel(f"🤝| {self.project_name} | {self.spots}")
collab_channel = bot.get_channel(collab)
print(collab)
print(collab_channel)
(this is not the actual code but the print results are:
🤝-newcollab--50000
None ``` so i created a channel but how can i get the channel id?
collab.id
collab_channel = bot.get_channel(collab) is unnecessary. collab is already a TextChannel object
oh okay thx
AttributeError: 'int' object has no attribute 'set_permissions'
i got the channel id but now i get this error
because collab.id.set_permissions makes no sense
you can't use set_permissions method on a number
you do collab.set_permissions since collab is the TextChannel object
yea but now i switched functions and now the only thing i have is that channel id
also, you should be able to set the permissions in create_text_channel
!d discord.CategoryChannel.create_text_channel
await create_text_channel(name, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`Guild.create_text_channel()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.create_text_channel "discord.Guild.create_text_channel") to create a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") in the category.
see the params
whats difference between a client and a bot?
yeaaa. i just like to keep comps seperated.
bot = discord.Client()
lol
its just a fancy name?
not entirely
commands.bot()
commands.Bot() is different
im asking ab this
we can use prefix in this one
how is that different from discord.client()
i pretty sure bot is just an extension of Client
bot is same as client the difference is bot comes with commands. its automated for you compared to using client and manually having to handle the events
ok
commands.Bot is just a subclass of discord.Client with prefix commands related extensions
discord.ext.commands.Bots have the concept of commands built into the class, so you can have command handling and other stuff that is related to bot users. discord.Client is more abstract and has no concept of commands, only event handling, so you have to do these in on_message events for message commands, and on_interaction (I think it was called that) for slash commands
more like a command handler
you can do app_commands without commands.Bot in discord.py, it works with CommandTree structure
ty now that clears it up, im just reading the documentation before i do something
With discord.ext.commands.Bot, you can also have cogs and command groups (and also slash command groups)
Because discord.ext.commands.Bot has the concept of cogs and (slash) command groups. Same thing with extensions.
Guys i want to make a library realted to discord.py that helps making bots using dpy easy
Can anyone tell what type of library should i make?
Any idea?
Maybe something around the component system
The diffrence is that discord.Client represents the current connection between your bot/application and discord, it is the class responsible to interact with the discord API, discord.ext.commands.Bot instead represents the bot itself, with all his components
in the end, Bot is both a subclass of Client and GroupMixin that provides the functionality to manage commands
Client also represents the bot, Bot is merely an extension for prefix cmds
Of course, since client communicates with the API it is the bot too
If you interface the GroupMixin class with the Client class you will be able to manage prefix cmds without the use of the Bot class
is there a way to give custom color to ButtonStyle then just using the predefined one?
class Hello(commands.Cogs):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(guild= bleh)
async def hello (self,ctx):
Function
def setup(bot):
bot.add_cog(Hello(bot))
Just started using cogs, what am I doing wrong here ? Ignore the typos and indentation error if any, it isn't a copy paste.
Are you using discord.py 2?
Pycord
Ok, you have to add the bot argument in the setup function's parameters
My bad as said not copy paste, forgot to write
It seems fine to me. Did you get any errors while loading it?
Nope
Let me share both files a sec
class Hello(commands.Cog):
def __init__(self,bot):
self.bot= bot
@discord.slash_command(guild_ids=config.GUILD, description="Says Hello.")
async def hello(self,ctx : discord.Interaction):
await ctx.response.send_message("Hello")
def setup(bot: discord.Client):
bot.add_cog(Hello(bot))
@bot.command()
async def start(ctx: discord.Interaction):
for filename in os.listdir('./Commands'):
if filename.endswith(".py"):
bot.load_extension(f'Commands.{filename[:-3]}')
await ctx.channel.send("Bot loaded.")
Could one of you two ping me when you're done?
I don't wanna interrupt with my own problem 
What's wrong with it?
i dont see the slash command
so probably cog not getting loaded ?
i want to edit a embed when a button is clicked any example?
did you sync it?
I don't know if you have to sync commands in Pycord
.
Thanks!
Is there a way to either:
Delay the execution of something (like using time.sleep()) without making the whole program stop
Orrrr use a database to assign a 'tag' to a user for x amount of time, and after that time is up it executes some stuff?
there's asyncio.sleep
would it be accurate in case of multiple such executions ?
i think i read somewhere that it might not be
don't see an issue with it until the program exists before the sleep task is completed
but yes a db with a .ext.tasks.loop is lot better
Could you point me to a place where I could read up on it?
I’m familiar with how DBs work… just not that familiar
you can save the user id of user and the time at which the role is to be removed
then run a task loop every second which removes roles for users whose roles are to be removed
I see, is there a place to read on it though?
An API or doc?
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Epic
Thanks, Sarth 
how to edit an embed using the button please help
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
how do i make an error command so that if all the args are not fulfilled it sends a message
for the love of the god throw an example or something please
class TicketReason(discord.ui.View):
def __init__(self, user):
self.user= user
super().__init__(timeout=None)
@discord.ui.select(placeholder="Choose your ticket reason", options=[
discord.SelectOption(
label="select1", description="select1"
),
discord.SelectOption(
label="select2", description="select2"
)
])
async def help_callback(self, select, interaction: discord.Interaction):
select.placeholder = f"Reason: {self.children[0].values}"
reason=self.children[0].values
if reason == 'select1':
channel=await interaction.guild.create_text_channel(name=f"{interaction.user.display_name}┃Ticket", topic=f"{interaction.user.id}")
await interaction.response.send_message("Ticket Created")
embed=discord.Embed(title="טיקט חדש!", description="פתוח")
embed.add_field(name="סיבה:", value=f"> `{reason}`")
await channel.set_permissions(interaction.guild.default_role, view_channel=False)
await channel.set_permissions(interaction.user, view_channel=True)
await channel.send(embed=embed)
if reason == 'select2':
channel=await interaction.guild.create_text_channel(name=f"{interaction.user.display_name}┃Ticket", topic=f"{interaction.user.id}")
await interaction.response.send_message("Ticket Created")
embed=discord.Embed(title="טיקט חדש!", description="פתוח")
embed.add_field(name="סיבה:", value=f"> `{reason}`")
await channel.set_permissions(interaction.guild.default_role, view_channel=False)
await channel.set_permissions(interaction.user, view_channel=True)
await channel.send(embed=embed)
@bot.command()
async def ticket(ctx):
view = TicketReason(ctx.author)
await ctx.reply(view=view)```
```[2022-10-07 15:23:09] [ERROR ] discord.ui.view: Ignoring exception in view <TicketReason timeout=None children=1> for item <Select placeholder='Choose your ticket reason' min_values=1 max_values=1 options=[<SelectOption label='select1' value='select1' description='select1' emoji=None default=False>, <SelectOption label='select2' value='select2' description='select2' emoji=None default=False>] disabled=False>
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 207, in help_callback
select.placeholder = f"Reason: {self.children[0].values}"
AttributeError: 'Interaction' object has no attribute 'placeholder'
[2022-10-07 15:24:16] [ERROR ] discord.ui.view: Ignoring exception in view <TicketReason timeout=None children=1> for item <Select placeholder='Choose your ticket reason' min_values=1 max_values=1 options=[<SelectOption label='select1' value='select1' description='select1' emoji=None default=False>, <SelectOption label='select2' value='select2' description='select2' emoji=None default=False>] disabled=False>
Traceback (most recent call last):
File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "c:\Users\PC\Desktop\AlonDaPro Bot\main.py", line 207, in help_callback
select.placeholder = f"Reason: {self.children[0].values}"
AttributeError: 'Interaction' object has no attribute 'placeholder'```
Would the level 6 thing able to be written while checking database
And how would I go about making it
Writing text onto a template seems hard with python