channel = channel[0]
for channel in guild.text_channels:
if channel.name.startswith("mm-"):
await channel.delete()
await ctx.send('Channel deleted')
channel = discord.utils.get(ctx.guild.channels, name='priv-logs')
embed=discord.Embed(title="Logging", description=f'[LOGS] Middleman channel closed by <@{username}>', color = random.choice(colors))
await channel.send(embed=embed)
#discord-bots
1 messages · Page 1125 of 1
instead of random.choice(colors) you could just do discord.Color.random()
so
wait a sec
for i in guild.text_channels:
if i.name.startswith("mm-"):
await i.delete()
await ctx.send('Channel deleted')
channel = discord.utils.get(ctx.guild.channels, name='priv-logs')
embed=discord.Embed(title="Logging", description=f'[LOGS] Middleman channel closed by <@{username}>', color = discord.Colour.random())
await channel.send(embed=embed)
i only wanted it to do it for the channel that the command was sent in, so if it didnt start with mm- it would do the else statement
then yes ctx.channel, no need to loop through
with my old code?
where's your old code
nvm not that
what do i add to
for i in guild.text_channels:
if i.name.startswith("mm-"):
await i.delete()
await ctx.send('Channel deleted')
channel = discord.utils.get(ctx.guild.channels, name='priv-logs')
embed=discord.Embed(title="Logging", description=f'[LOGS] Middleman channel closed by <@{username}>', color = discord.Colour.random())
await channel.send(embed=embed)
then
just don't loop through guild channels?
Only check if ctx.channel starts with it
if ctx.channel.name.startswith("mm-"):
await ctx.channel.delete()
channel = discord.utils.get(ctx.guild.channels, name='priv-logs')
await channel.send('Channel deleted')
embed=discord.Embed(title="Logging", description=f'[LOGS] Middleman channel closed by <@{username}>', color = discord.Colour.random())
await channel.send(embed=embed)
how would u do ctx.send
if channel is deleted
so much spoonfeeding here smh
Learning from examples isn't a bad thing.
this is just the beginning
Wdym if channel is deleted
You basically talked Minecraft enchantment language to him if your comment was a bit more beginner friendly I'd agree.
If a channel is deleted you can't send smt there
How would you di ctx send if channel is deleted
It's normal here
channel.send*
after deleting channel
But
Look
bro🥲
To another channel or to deleted channel?
to the deleted channel
Smh
scroll up and see
lol if that's enchanting table language then they probably shouldn't be doing discord stuff
How are you going to send something to a channel it doesn't exist 🙂
Ash he/she is getting a new channel.
...
My bad
😭
I know perfectly fine what you said but for starters it's not and if you got something to complain about in this channel then go to staff instead of bothering other members.
If they don't know python they need to learn python not Discord.py
It'll lead to nothing
It's normal for newbies to ask dpy questions here
Anyone is allowed to ask questions here, regardless of their skill level.
Well, I learnt Python while doing discord.py
Same indeed.
:v
So yea. I can safely say that many people can learn and excel in Python, while learning it with discord.py
Welp
u forgot tkinter and pygame👀
ew
ayo
id say tkinter and discord.py fs
pygame
good for OOP practice
imo
yes sprite classes
even ursina
mhm
is good but nvm
- while loops
that too
can u help me in #help-chocolate plz
I never used either
Also, for me, pygame < arcade
Many of the frequent people here, learnt that way
totally not me
I learnt that way
i used the rpi game debian os i forgot what the name was tho
Nice, I never used a rpi
weirdos
yes, and I know im weird
It was a fun way 🤷♂️
Idrc what anyone thinks about the same, what matters is that I know enough Python to make projects
don't make me start now, you didnt even know what typecasting is 😔
I did...
Wym
I mean, I was the one who told the other person what's type casting, yesterday or smth
Hun bun 😔
I mean, I don't know enough terms, but at least I was able to devise the meaning.
still
ic
🫂
Well, there's always some deficiency when u don't learn programming professionally in school, but u don't need to use those types of terms when u r writing the program itself, but nvm
dont get me started on what we learn at school lmao
Same. I'm still learning what are lists and if statements
for i in range(len(l))
if (condition):
name = input("Your name ")
print("Hi", name)
This is what I learn at school 😄
fuck school python
But it's OT
i know, just pointing out unpythonicity in schools
thats what every cbse school teaches👀
hmmm... "unpythonicity"
u coined a new term
Python't
pythonot
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
damn you ryuga, smooth but aughhhh
Heyo 👋
Lmao same my book have python chapter in which they teach how to define var and type() and just operators
Hi
who learns at school anyways, home is the place where you start
@bot.event
async def on_member_join(member):
role = 468197591176183809
await member.add.roles(role)```
Why doesn't that work?
oops
still doesn't work
!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.
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 the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission 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.
@bot.event
async def on_member_join(member):
role = member.guild.get_role(468197591176183809)
await member.add_roles(role)``` still doesn't work.
What happens?
@slate swan python intents = discord.Intents.default() intents.members = True
@upbeat gust When someone joins, No role assigned to him
that's... default...
i‘d just go with intens.all()
Are you passing that to you bot though?
a lot easier
no need but sure easier
yeah
!d discord.Object
class discord.Object(id)```
Represents a generic Discord object.
The purpose of this class is to allow you to create ‘miniature’ versions of data classes if you want to pass in just an ID. Most functions that take in a specific data class with an ID can also take in this class as a substitute instead. Note that even though this is the case, not all objects (if any) actually inherit from this class.
There are also some cases where some websocket events are received in [strange order](https://github.com/Rapptz/discord.py/issues/21) and when such events happened you would receive this class rather than the actual data class. These cases are extremely rare.
x == y Checks if two objects are equal.
x != y Checks if two objects are not equal.
hash(x) Returns the object’s hash.
ok so i have this view, and it has buttons, and when the user clicks the buttons, even tho im editing the embed, and changing it, it still says inter failed. i remember i have to do something extra here, but what exactly?
Are you responding at all? (Defer)
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
@alpine cove python @bot.event async def on_member_join(member): role = discord.Object(468197591176183809) await member.add_roles(role) ?
await defer(*, with_message=..., ephemeral=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
Changed in version 2.5: Raises [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") when an interaction cannot be deferred.
Is Disnake better that nextcord? Should've asked thid a while ago
yes disnake is better than nextcord
hi, anyone know why this is raising 'function' object has no attribute 'callback'? these decorators seem to be the cause
@lightbulb.implements(lightbulb.SlashCommand)
@lightbulb.set_help(docstring=True)
@bot.command()
async def ping(ctx: lightbulb.SlashContext) -> None:
(iusehikaribtw)
Damn, guess I'll switch to that
rhx
tried changing the order of these a bunch of times
it's @bot.command not @bot.command()
np I saw that yesterday and thought it was weird that's why I know.
it's not weird 😔
@bot.event
async def on_member_join(member):
role = discord.Object(468197591176183809)
await member.add_roles(role)``` Should be this?
looks good, maybe add id= to the discord.Object param
still raises same err
is the order incorrect
Still doesn't work..
i am a fucking idiot i forgot lightbulb.command
what error does it raise?
why don't you use the Bot to get the role instead of using Discord.Object
just fyi, that you need a @bot.command and a @lightbulb.command(...)
why get role when you can just use the snowflake?
that's kinda dumb why
why not just one decorator
any reasons?
it's a fork of Discord.py (already this should be enough) and is updated to support the latest features of Discord
even discord.py does that
Aren't they both forks of dpy??
yes
so, I'm asking why disnake is better than nextcord in their opinion
just overall had better experience with it
ok cool
more = better
what happened to "simplicity is key"
semi-counterpoint: multiple component decorators is simpler than one large complex one
okay i get it, but what's the difference between lightbulb's deco and BotApp's deco
I'm making a decorator for the on_message() event, how can I pass an argument to the function that the decorator refers to? For example, when working with a command, I pass ctx: commands.Context
guys what r cogs
The callable that is returned from the decorator needs to have the arguments of the function
A group of commands and events and whatnot
You need subclass the Cog class to create your own cog
Setting it up depends on where it is written
ok
Typically you would have one cog per file, separated from the main bot file and separated from each cog file, and load them as extensions
And? How to write an argument
What is not understood?
like i have a my school friends server in that i added a bot and in that bot i am trying to add a game
for that game i need to input from user
like user : $<game> bot : xyz user : this is the input which i need
How to write an argument to the function that the decorator refers to when processing on_message(). Similar to ctx: commands.Context when calling a command
What are trying to do with a command context in an on_message event
async def <cmd name or add aliases>:
body```
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for "(in Python v3.10)"). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError "(in Python v3.10)") for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)") containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
this? @real grail
no
then
What's the purpose of this?
I mean, on_message already has its intended argument: The received message
def allowed_rewards_from_messages():
async def func( here ):
if message.channel.id in [839244428271026196, 839228777174401034, 842798995146801202]:
return False
else:
return True
return commands.check(func)```
(decorator)
I specifically wrote ._.
are there any discord.py sink extensions? Like voice recv for d.py. I dont want to use pycord…
I need to pass the message context there
The last time I checked, no, sadly
And, well, you can't add a command check to an event anyway (I see you are using commands.check)
ok, this is a random error, fixed it. But how do you pass the argument anyway?
Just use the function whenever you need it, and you can simplify it to this by the way:
def check(message: discord.Message) -> bool:
return message.channel.id not in {id1, id2, id3}
Do you know how to use decorators?
Yes
Then you should be able to understand that the parameters of the function returned by the decorator are supposed to match the parameters of the decorated function
What do you want to do after checking the channel the message was sent in
def allowed_rewards_from_boosts():
async def func(message: discord.Message):
if message.channel.id == 957877880065499196:
if message.type == discord.MessageType.premium_guild_subscription:
return True
else: pass
else:
return False
return message.check(func)```
New weird bug in another block of code (return message.check(func)
NameError: name 'message' is not defined)
You should be returning func, not message.check(func)
But what are you trying to do with this
It will simply not execute the on_message event's function
@bot.event
@Element_permissions.allowed_rewards_from_messages()
async def on_message(message):
await bot.process_commands(message)
if message.author.bot == False:
balance_member = Element_connections.sqlite3_SELECT(0, message.author.id)
reward = int(random.choice("12345"))
balance_member += reward
Element_connections.sqlite3_UPDATE(balance_member, message.author.id)
print(f"Member {message.author.name} was rewarded for message: {reward} brilliants.")
else: pass```
(I will also transfer the check for the bot to the decorator)
How do I make it for member argument first, then after for it to look for reason?
Because if I don't state member, it will say "You have to specify a reason"
So I need it to check for member first, is that how I do it?
Not sure why it highlites me this?
Three things:
- I would keep the code inside the event and not separate it into decorators because it only complicates things with no visible benefit
- Move the
await bot.process_commands(message)to the end of the event else: passdoes nothing and can be removed.elseis always optional
Thank you, I know about else, it’s more convenient for me to navigate simply
Are you using commands or an event
command lol?
Is it discord.py
I wonder if it has type conversions for command arguments like discord.py
Because you could do it really easily then
It does. Since it's a discord.py fork
Try
async def kick(ctx: disnake.Context, member: disnake.Member, *, reason):
...
The arguments should be automatically type converted and reason should be a string
This lets you rid of the ifs you have
And it's also recommended because if the arguments are wrong you can handle them with whatever disnake's command error handling system is
Wait what?
Remove the try-except thing
Also fun fact: You can use ctx.send instead of ctx.channel.send
So just this huh?
I think so.
Yeah I don't know where it is at in disnake
commands.Context
Yep
How did you ran the command
So the neat part is you can handle this exception with a command error handler
I don't know how it goes in disnake, but if it's a fork of discord.py then it must be similar to
@kick.error
async def on_kick_error(ctx: commands.Context, error):
if isinstance(error, commands.errors.MissingRequiredArgument):
... # handle this specific error
This is specific to that command
You could have a global error handler
Hey, does anyone know how to create a channel upon interaction of a button?
I can get it working with a command, but I'm not sure how to with a button
Also fun fact: because you are using these type things, the member argument can be a mention, an ID, a username or a nickname (in quotes if it has spaces)!
eh I know but not sure how to convert it all
It is converted for you by the fact you used type hinting
member: disnake.Member will always be a disnake.Member object, or an error will be thrown and you would need to handle it (it's commands.errors.BadArgument if I am not mistaken)
^
I don't know
I'm a dinosaur fossil from before the alternative wrappers when discord.py has died for months
I know nothing about anything new
I should probably try to
Yeah
@bot.command()
@commands.has_role("Server Owner")
@commands.has_permissions(kick_members=True)
async def kick(ctx, user:discord.Member, *, reason="No Reason Given"):
try:
await user.kick(reason=reason)
embed = discord.Embed(color=discord.Colour.red(), title="",description="")
embed.add_field(name="Kicked:", value=f"""
The member **{user}** has been kicked, Reason: **{reason}** """,inline=True)
await ctx.reply(embed=embed)
await user.send("You have been kicked from the server!") ******
except:
embed = discord.Embed(color=discord.Colour.red(), title="",description="")
embed.add_field(name="Kicked:", value=f"""
Error""",inline=True)``` That doesn't send the message to the user.
You're using it in the reply
Oh I thought you meant the embed
Try kicking after sending the message.
Also the user might simply have disabled DMs
i tried that but it doesn't even kick or send the message.
What does it do then
nothing
An error might have been thrown
oh wait that worked now, idk how that didn't work before
So Im Trying To Make My Bot And I Have Lost 1200 Lines Of Code... Is Replit Suddenly Broken Or Something? All Im Seeing Is The Outline Of The Boxes
How do I get guild name? (public bot)
kinda just guild.name
That depends on where you get the guild from
But essentially, 
well it's not specified, since it's public
But Wth, WHy
What guild
ctx has a guild attribute
It's the guild the command was run in
I don't know what it is for private messages
Can Someone Help?
Probably None or something
!replit
!heroku
How to say the server name in the message?
await user.send("You have been kicked from the server! **{guild.name}**")``` ?
u forgot the f b4 the string like f'...'
Ye But Kinda My Only Option On This Computer, Chromebook
@paper sluice i get this error "guild" is not defined
define guild then
If it's in a command then use ctx.guild
Chromebooks can't run python?
Ye
huh?
i believe they have a linux based kernel
Wdym?
what specs
@bot.event
async def on_member_join(member):
await member.add_roles(468197591176183809)``` that doesn't set the role
Oh... Idk
what doesnt?
Chrome os is based on linux
and linux comes with python pre-installed since its heavily dependent on it.
So How Do I Run Python?
python should work fine have you tried it?
you see a terminal?
@paper sluice it doesn't set the role
enter python -V -V/python3 -V -V there
Terminal? Were Can I Find It
guild = ctx.guild
@client.event
async def on_guild_join(guild: disnake.Guild):```
How do I make it so bot makes a channel on-join? (custom name)
Also is there a way so It gets the ID of same so I can use it for logs, instead of using the name of the channel?
No Idea, Only Used Python To Make My Bot, My Language is LUA
anybody know how to create a text channel upon an interaction of a nextcord button? I can create channels with the command but not with the interaction, and its pretty pointless if it only creates it on command if its for a server ETC.
So?
do member.add_roles(discord.Object(id=....))
@client.event
async def on_guild_join(guild: disnake.Guild):```
How do I make it so bot makes a channel on-join? (custom name)
Also is there a way so It gets the ID of same so I can use it for logs, instead of using the name of the channel?
channel = await guild.create_text_channel(...)
channel_id = channel.id```
import requests
import json
def channel_messages(channelid):
headers = {
'authorization': 'TOKEN_HERE'
}
r =requests.get(f'https://discord.com/V9/channels/{channelid}/messages', headers=headers)
jsonn = json.loads(r.text)
for value in jsonn:
print(value, '/n')
channel_messages('')```
i am trying to get json output but it just gives an error
pffttt
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
its called crosh/ ctrl+alt+T
crosh lmao
You know how to make an channel upon interaction of a button anyone? nextcord btw
Just Got Replit
Have you tried printing r.json()
your are missing bearer type py headers = { 'authorization': "Bot TOKEN HERE" } The Bot text shall be there
got it, Now?
.
i am not much of coder i just saw this somewhere can you please tell me where do i put it?
Still doesn't set the role
any errors?
Anyone know how to create a channel upon interaction of a nextcord button? (A ticket bot is what im talking about)
Anywhere after assigning r the return value of request.get
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.
The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.
Note
Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
How do I get that channel now?
i will try thank you
no
I know that but I'm not sure how to do it with a nextcord button
And nextcord buttons and discord.py buttons work the same??????
I Got A Error, Unknown Command
It's channel
syntax might be a little different, but they should do the same thing
Yeah I know how to do it with a command which is pretty pointless but im not sure how to with a button, maybe we could try to do this together?
? Interaction.guild.create_x_channel
Well where do you intend to save the fact this guild now has this channel
Let me try
You need to manage a database or something
@paper sluice
do you have dev mode enabled?
But look, you don't need database? It's working with "get channel name" and gets that channel by the name
but I am trying to get that channel with the ID
Dev Mode?
incase it is renamed afterwards or smth
show code
whole bot code?
Well you can't magically know what the ID is without storing it in someplace you know
just the place where ur adding the role
@bot.event
async def on_member_join(member):
await member.add_roles(discord.Object(id=468197591176183809))```
someone joined the guild and they didnt get the role?
how it works with channel name tho
@paper sluice yes
oh nvm..
and there are no errors in ur terminal?
yes
try
member.add_roles(member.guild.get_role(id))
Retrieve the channel using its name unless you don't know it, but it seems you do, because you are creating it with a string literal
i tried but it only gives this error
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
Try printing r.text
It should be JSON I think, so r.json() should have worked, I think
Trying to make a logs system for a public bot, without a database bc I don't know a shit about it tbh
It's good that you learn it now then
nope
So nothing without a database huh, lol
did u restart the bot?
yeah
I mean a database can be a simple txt file
import requests
import json
def channel_messages(channelid):
headers = {
'authorization': "TokenHere"
}
r =requests.get(f'https://discord.com/V9/channels/{channelid}/messages', headers=headers)
jsonn = json.loads(r.text)
for value in jsonn:
print(value, "/n")
r.json()
channel_messages('channelid here')```
i tried this
idk then, sry
even I gave the bot all permissions via the server
Remove the
jsonn = json.loads(r.text)
for value in jsonn:
print(value, "/n")
and replace r.json() there with print(r.json()) and tell me what you get
I am not sure whether this will even work for you, because using Discord API is supposed to involve a websocket or something, I think
it's giving the same error i just wanted to get all the channel ids from a server but don't know how to code a bot
I thought you wanted to get all messages in a channel
@void kite
nope, REST API can work without a websocket
You're supposed to use https://discord.com/api/v9/guilds/{guild_id}/channels instead of https://discord.com/V9/channels/{channelid}/messages then
i didn't understand
By the way version 10 supposedly exists so you can use v10 instead of v9
if your token is nevergonnagiveyouup , this is how your headers should be -> ```py
{
"Authorization": "Bot nevergonnagiveyouup"
}
@void kite Do you have a bot user? You need to use its token
error?
i am using that
Can you show what you get from printing r.text
raise RequestsJSONDecodeError(e.msg, e.doc, e.pos) requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
whats the endpoint you used?
Are you using this URL https://discord.com/api/v9/guilds/{guild_id}/channels
yes
Well you need to change your function to accept a valid guild ID of a guild that the bot user is in
you're missing all the requirements arguments to provide
Actually I don't think the bot user needs to be in said guild
https://discord.com/developers/docs/resources/channel#get-channel-messages
especially the limit
Discord Developer Portal
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
How to send a random message from messages list?
i am really confused since i have negetive experience in coding
They said they wanted this
i just wanted to get all the channel ids from a server
why are they using the /messages endpoint above then
!paste @void kite share the code here and also send a screenshot of the exception traceback
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.
why don't you just use an api wrapper instead of doing this.
Oh I'm stupid
it's not an actual bot it's a user bot
Wait I ain't
no help then
!rule 5 self bots are against discord tos
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
No idea
also, thats the reason why "Bot token" was failing
!d random.choice
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
Not necessarily #discord-bots related
it stops the command working, yes but if i do it again it will send nothing in the chat
its just alex.error
Please don't post things with the r word. It's ableism and not welcome here.
oh i didnt know im sry
okay thnaks
wont happen again
Thanks 😄
Would you mind editing your code block to not have it in there please?
yeah sure
did :)
You're awesome, thanks!
What does this mean?
those functions are inside a class right?
Yeah
they must take self as the first argument
and u call them using self.function-name(args) inside ur function
Could I do await log(self,ctx)?
u could, its not necessary, just do self.log(ctx)
It says self.log(ctx) was never awaited
How can I make the bot read from txt file and send a random line from that file?
@bot.command()
async def rand(ctx):
with open('file.txt') as f:
await ctx.send(random.choice(f.readlines()))```
if u want to invoke a command from a different command, use commands.Context.inoke
!pypi pastebin
@deep osprey
you need to have an api key on your dev page though
and to scrape pastebins you also need to have a premium membership
are there any free websites?
How would I send that embed to a specific channel, because it won't let me do channel.send(embed = embed), because I am using ctx
Why are you using client in cogs
Too lazy to change it to commands now
ctx.invoke(self.bot.get_command('log'))
Hello, i have VPS hosting, and when i turn off my pc my bots going offline. and how i can fix 27/7 ?
?
??
What VPS is that?
do you mean you have replit?
lmaoo
||modified clients are against tos||
nice
you're importing random twice in the same line
thanks, fixed it.
guess im bad 😈😈
yes very 
@bot.event
async def on_member_join(member):
await member.add_roles(member.guild.get_role(468197591176183809))``` Why doesn't that set the role?
When you joined your server with an account, it didn't give it the role?
Got intents?
yes
yes
Got errors?
nope
do you run bot
yes
do you have another on_member_join event?
nope
!paste can you paste your complete code here
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.
Guys how can we make a comamnd that
When i reply to a message
And in reply i type >translate <language name> so it translate the message to which I replied
How can I do that?
(Pls help me everyone insult my bot and say it useless so i wanted to make something new)
if user types #discord-bots then i want to get its id
Ye
is that a command?
yes
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
Pls help me if it's possible
you can typehint that command argument as discord.TextChannel and then use argument.id
async def command ( context, channel : discord.TextChannel):
id = channel.id
but how do i get id of any channel ,i mean if a user types #announcements i want to get that channels id and see its last msg
see the id variable there....
but-
oh
!d discord.TextChannel.last_message for the last message in that channel
property last_message```
Retrieves the last message from this channel in cache.
The message might not be valid or point to an existing message.
Reliable Fetching
For a slightly more reliable method of fetching the last message, consider using either [`history()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.history "discord.TextChannel.history") or [`fetch_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.fetch_message "discord.TextChannel.fetch_message") with the [`last_message_id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.last_message_id "discord.TextChannel.last_message_id") attribute.
does lightbulb.SlashContext store the message?
Guys how can we make a comamnd that
When i reply to a message
And in reply i type >translate <language name> so it translate the message to which I replied
How can I do that?
(Pls help me everyone insult my bot and say it useless so i wanted to make something new)
you mean the interaction which invoked the context?
@robust fulcrum
you can ctx.message.reference to see the message which it was replied to
nah just the response
I not understood what you mean
you get a ResponseProxy returned from Context.respond
await ResponseProxy.message() gives you the message
ah ok
Why is hikari better
the message which invoked the command (ctx.message) would be a discord.Message object
and that object has a reference property which gives you what message it was replied to.
So i can store the replied message in a variable and get translate
is mercedes better than audi?
bot [but] beyond that it's a personal preference
- Emzi0767#1837
Better cache, everything is built so you can make your own impl of each part if you want. Customizable cache as well as working well with intents, doesn't break if discord adds a new field to some object (something that d.py has done in the past). Hikari will support cython speedups for the base impl, which is basically python compiled to C, which makes it run on steroids. Overall, faster than d.py and built to last and be extendable
- davfsa#7026
Consistency, strictness, strong typing, modularity, composition and cache independence is what makes Hikari better than d.py
- vicky5124#2207
What is this...
your dictionary does not have that key
nowPlaying[key] #raises a KeyError
nowPlaying.get(key) #returns None```
Ye
!e ```py
d = {}
print(d["non existent key"])
@slate swan :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 2, in <module>
003 | KeyError: 'non existent key'
Type correct spelling of key if it's there
Like uppercase
woah
Or lowercase
integers have punctuation cases
;-;
the key name here is an integer, there is no upper or lower case
this is the key bruh
they are accessing the key using an ID
Ok
don't tell me youre switching
^
Can anyone help me out with my problem in #help-chocolate ? its about trying to log slash commands
but hikari FTW im biased
samez
hey yall, I am working on my server's bot. I'm thinking of creating a cache for some of the commands where bot needs to poll a slow loading site.
but I'm kind of unfamiliar with how to call cogs.
example.py:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# In this case, discord import is not needed, in some cases it may be.
# import discord
from discord.ext import commands
class ExampleCog(commands.Cog):
"""The ping to your pong"""
def __init__(self, bot):
"""Save our bot argument that is passed in to the class."""
self.bot = bot
@commands.command(
name="ping",
help="The pong to your ping, let's you know that the bot is alive.")
async def ping(self, ctx):
await ctx.send("Pong")
def setup(bot):
bot.add_cog(ExampleCog(bot))
and my bot.py looks like this:
@bot.event
async def on_ready():
#set playing status
await bot.change_presence(activity=discord.Game(name='Wengerball'))
print('Logged on as')
print(bot.user.name)
print('----')
try:
f = open('token.txt')
token = f.readline()
f.close()
load_cogs()
bot.run(token.rstrip())
get_fixtures()
except Exception as e:
print(getTimestamp() +"setup error\n")
print(e)
sleep(5)
should i create a cog called "cacheMaker" or something?
and how could i tell my bot to call the "ping" command internally?
Why will you want to compile a bot code to C tho
Ye
to be faster? it's written right there
Do I have to replace everywhere I do nowPlaying[ctx.guild.id]?
yes
How do I use it?
I meant, it's not like u r making a game or smth that u need such a speed boost
or just add the key in ur dict..
How do I do that?
this isn't a need, more of a feature/add-on
dict[key] = value
= value?
do you know how dicts work?
No
.rp dict
#sir-lancebot-playground message
learn that first before using it
my bot isnt recognizing its prefix help
This is probably a good intro article from that: https://realpython.com/python-dicts/
Also it makes me happier than it should that someone else used the .rp command
i saw u use it once, and i thought its actually pretty helpful
can you show your code?
in code
ctx.channel.id
okay
client = commands.Bot(command_prefix='.')
@client.event
async def on_ready():
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="One Piece"))
print("ready")```
u dont have any commands, so the bot wont do anything when do type.something
i have commands, @client.command() async def ping(ctx): await ctx.send("pong!") it used to respond but now it just doesnt
did u run the bot?
yep
im using an on message event to automod for links and that works perfectly. its just commands
ya change the @bot.event to @bot.listen() on ur on_message event and it should work
alright lemme test
thank you so much, it works perfectly
👍
if I want to get the arguments that I pass to a slash command, what am I supposed to add to the ctx.command? ex: \pick choices: 1 2 3 I want it to print that, but its only getting \pick
what library are you using?
slash commands dont even start with a backslash
discord-py-slash-command
backslash command 😳
I'm sorry yea I meant /
yes
consider upgrading to discord.py 2.0
already referenced ryugA
mhm Ashley suggested too
Ryuga
ya because, u should....
try: convince()
except: try_again()
just asking, why though? just curious to know what discord.py 2.0 offers over the d-p-s-c
finally: giveUp()
snake case ofc not
everything, slash commands are built in, there are buttons and other ui stuff
#discord-bots message
this goes through most of them
and the best part, because dpy is a well known library. you are more likely to get help when u get stuck
yes I did go through that 👍 though I'd have to rewrite everything...
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
ctx.send(msg.jump_url)
not everything, ur commands pretty much stay unchanged, just the startup and loading cogs have breaking changes and rest are minor changes, u can fix them eventually
well, if I'm outdated, guess I gotta upgrade anyways
ah okay
what do i do
await ctx.send(...)
Guys how can we use discord.Message.reference?
what do u need it for?
Replied message
Like i replied to this message and i want the message to which I replied
!d discord.Message.reference
The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.
New in version 1.5.
u can do this message_object.reference to get it
Will it give me the message to which I replied?
yes
translate english
So it will work?
it should
I'll use it to translet the message to which I replied
@commands.command()
async def get(self, ctx):
reply = message_object.reference(ctx.author)
await ctx.send(reply)
Will it work?
@paper sluice
Cython is faster than python with Cpython core
!d discord.Message.reference.message_id
Not gonna happen.
No documentation found for the requested symbol.
Ik, but doesn't really make a difference in a.... discord bot, imho
Makes much more sense when u cythonize games
no, in this case you would code ctx.message.reference
and it an attribute, so you can't call it
indeed, but still if you want to, its an option
who makes games in python anyways
imagine not grinding hours for 0.1 ns performance boost
id say 2d games are pretty common, 3d not so much
It gave me
<MessageReference message_id=991366912011415605 channel_id=989139989671579658 guild_id=978569921321635840>
I want the message not this
what do u want to do it, get the text right?
Ye
do reply.content
ctx.reply.content?
Arcade and PyGame 🥺
no
@commands.command()
async def get(self, ctx):
reply = ctx.message.reference
content = reply.cached_message.content
...

if the message is not in the cache, you will have to fetch it
Discord client
Mod
plugin*
Whatever
idr if bluecord is a mod or plugin
Nice
where?
💀
See this screenshot
Ye
Plugins are extensions
damn sparky, you're so intelligent
smartky
pffttt
Thanks
that was sarcastic, dw
Is it just me or the nicknames ya'll give do suck?
I'm sure I've never given a nickname to anybody
indeed
I knew that was gonna come up one day
dont start again
😭
I'll just shift to my middle name instead
Hi
ash ketchum ley
hello
..........
what's ley for?
Nice one
same question
this u?
ic Ash ley
lmao
absolutely
i would rather stick with ash Ketchum
u people do fortune telling 💀 👀
and I'm surely leaving if you guys continue
!ot <-- better channel
Off-topic channel: #ot2-never-nester’s-nightmare
Please read our off-topic etiquette before participating in conversations.
async def on_message(ctx):
if ctx.author.id == 912769756082352150:
print("nah jit trippin")
else:
for bad_word in bad_words:
if bad_word in ctx.content.lower():#.split(" "):
bad_word_embed = discord.Embed(title = "Link Sent", description=f"{ctx.author.mention}, Do not send that.", color = discord.Color.blurple())
await ctx.channel.send(embed=bad_word_embed, delete_after=10)
member = ctx.author
role = discord.utils.get(member.guild.roles, name="Timeout")
await member.add_roles(role)
channel = client.get_channel(991353012360597574)
await channel.send(f'{ctx.author.mention} has been put into timeout. Feel free to remove the role whenever.')
await ctx.delete()``` i have a banned words thing the filter works its just the message doesnt send when the user id is exactly that
Thanks
user id? what? send? you have a print in there
it doesnt send the message when the user id is that. the print works it just doesnt send whatever was typed
btw, if someone sends a paragraph full of your "bad_words" list, this is gonna send a message for each time
well that sucks
because you arent sending anything
so lets say my user id is that and i type "test" it wont send test but it will print nah jit trippin
because you arent sending anything it'll only print the text dude
could i add like await ctx.send(ctx.message.content)?
where do you even get the ctx from
on_message takes an argument which is an instance of a Message object
so those properties wont work
@bot.command()
@commands.cooldown(1,5, commands.BucketType.member)
async def invite(ctx):
if ctx.channel.id != 984872910961405963:
em = nextcord.Embed(title=f"You cant use this command here",description=f"Use the command please in [#984872910961405963](/guild/267624335836053506/channel/984872910961405963/).", color=0x00ff00)
await ctx.send(embed=em,delete_after=8)
else:
link = await ctx.channel.create_invite(max_age = 0, max_uses=0)
await ctx.send(f"Here is your invite {ctx.author.mention}: {link}")``` hi i just did this, how can i make that if i type my commands in an different channel the if ctx.channel.id statement will be ignored?
like only if I type it in another channel
yes it will be ignored
so do your stuff in the else
or just return the first ctx.send easy
Dear. threw the folder with the bot the bot does not work. what else needs to be done?
threw the folder?
probably he means uploaded the folder
I transferred it to hosting
Ketup what
Is there any way to keep my bot alive for free?
There is nothing free bro 🫂
discord bot hosting is like30 cents a month lol, and with that you at least get good service
thats not even a host
theres a few free hosts out there but the support is either bad or machines are bad
^^^
if you have a credit card you can get free vps hosting for 3 years
people have recommended me to switch from discord-py-slash-commands to just discord.py, but just wondering which is better between that and disnake?
Ok
what do you prefer sparky
I prefer disnake
lmao
i'd say Disnake too, for reasons.
not sure if ryuga said he preferred disnake or just guessed that sparky was gonna say it
Ryuga prefer nextcord
ew
huh?
i was talking about sparky
i prefer not making discord bots if you want to know
like refactoring to discord.py seems a bit of work, but apparently if I'm moving to disnake I'd have to change way less than I would have to for dpy
ryuga says dpy, he my man
is the @everyone role always = guild.roles[0]?
and at the end of the day it's gonna be a discord bot anyways
yeah
guild.default_role is easier to get
Yeah
thx
dpy, yea im most familiar with it. But im starting to like hikari
hikari
I mean discord.py
im thinking of writing a getting started with hikari guide because the old one got deleted
nice
ah sad
hikari, I choose you
moment
hikari is easy ngl
meh, stop
meh
offtopic, when did you guys get into coding?
i started 2 years ago, but i really started like 6 months ago
ah I see
Shi* WiFi
6 years ago cause school, i had no interest in the start
i started self learning 2 years ago
I made my raspberry light up an LED yesterday
we were taught java at school in 6th standard 
tell me the name of the school, ill sort them out https://cdn.discordapp.com/emojis/744349119061032970.gif?size=64
average indian ICSE schools
yeaaa started about 3 months back like srsly, never paid any attention otherwise, now I regret it, cuz I'd be kinda okay in html and java rip
i forgot html 💀
my html knowledge
<tag> some stuff <tag/>
well icse introduces you guys to hardcore stuff early on. cbse trash ngl looking back, too lenient
XD
but in reality, it's
<tag some stuff> some stuff <tag/>
cbse made me learn python stuff in 4 years, which can actually be learned in a month
just shut up 😔
bro ikr
scam
i actually prefer them not teaching programming, no one cares about it unless you go to college and the thing they teach is so bad that you are better of not learning. I didnt listen to a single lecture ( cuz online ) and im the best in my class in python
variable declaration
operators , datatypes
functions
file reading/writing operations
stacks
python MySQL connector
looll
ew
so uh yall just good in py or other langs too
I taught my friends python (with OOP) one night before the exam
pro
just good in js
Why does this not work?
elif not isinstance(channel.type, (discord.ChannelType.text, discord.ChannelType.voice)):
elif isinstance(channel.type, (discord.ChannelType.text, discord.ChannelType.voice)):
TypeError: isinstance() arg 2 must be a type or tuple of types
60% of my classmates still don't get it
It's <\tag>
thats not a type, thats an enum
exactly
How can i add color to code block in my code?
How
Sorry for disturbing
a
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
thx
```<enter language here>
```
I made an anti nuke/raid bot
nice 🎉
@slate swan
It works too
await ctx.send(
f"<python> test"
) like that?
No
💀
u dont include the < > thats there just to show that your supposed to enter things there
```py
Like this
Is it open source
in quotes right?
It’s gonna be public so, no.
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
when vim for discord 😔
Ohk
I was torturing them physically dw
That's css
Kind of
pro
css..?
I am something of a css myself
did you mean mentally? 💀
my command is not working
Nice
😳
Erotic indeed
mines too
Sad
@bot.command()
async def search(ctx, *, word: str):
ch = await ctx.channel.history(limit=500).flatten()
await ctx.send('searching through old messages...')
for msg in ch:
h = msg.content
if h.startswith('-search'):
continue
else:
if word in msg.content:
await ctx.send(msg.jump_url)
break
else:
continue
if word not in msg.content:
await ctx.send("didnt find anything")
my life is not working, can u fix it for me 🥺
nah just one little slap is all it takes, tested
its just not sending anything
🪛 done
bro 💀
wha-
!resouces i request you check this out, thank you
💀
god i suck
L
sauce bro
i know there will be some bias opinions but are there any real differences between nextcord and discord.py?
Import "discord.ext" could not be resolvedPylancereportMissingImports
That doesn’t help
did u install discord.py?
Also
yeah
of course nextcord is a fork of discord.py. Both have different implementations for slash commands. and of course the code for nextcord is written in a better way
I'd still prefer discord.py
@slate swan this
install dpy bro
ok
im using nextcord atm, was just trying to see if there was any reason to change that would hugely benefit
same issue
💀 thanks for the suggestion, ill try that in future
do u have a file in ur working dir called discord.py ?
no
Install it omg
you imported "discord.ext" is it not just import discord
then from discord.ext import ...
you don't need to import discord for that...

Hi
i've always done it that way 😄
i work to this everytime lol
It’s a good rule to live by
hello, im currently working on a ticket system for a server, how do i make sure only administrators can only see the ticket?
with the ui buttons, can you hide specific roles from seeing certain buttons?
set channel overwrites with admin
ok
Let me try
K
Is there a way to just make a private channel though?
Lemme check docs
Not sure really where to put the admin thing?
Could you type it up?
TypeError: Object of type Member is not JSON serializable
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Object of type Member is not JSON serializable
Yea
heads up and see your physique differences before doing the deed
@client.tree.command(description="Mute a specified username")
@app_commands.checks.has_permissions(ban_members = True)
async def mute(inter: discord.Interaction, member: discord.Member, *, reason=None):
guild = inter.guild
mutedRole = discord.utils.get(guild.roles, name="Muted")
if not mutedRole:
mutedRole = await guild.create_role(name="Muted")
for channel in guild.channels:
await channel.set_permissions(mutedRole, speak=False, send_messages=False)
await member.add_roles(mutedRole, reason=reason)
em = discord.Embed(title="Mute Action", description=f"{member.mention} has been muted for {reason}", color=0x00008B)
await inter.response.send_message(embed = em)
await member.send(f"You have been muted in {guild.name} for {reason}")```
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
File "C:\Users\Dom\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\app_commands\commands.py", line 380, in _extract_parameters_from_callback
raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'reason' is missing a type annotation in callback 'mute'```
parameter 'reason' is missing a type annotation in callback 'mute'
annotate it with reason: typing.Optional[str]
or reason: str | None if ur on python 3.10+
how can i make a bot command to get all the channel ids from a guild's id
!d discord.Client.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
!d discord.Guild.channels
property channels```
A list of channels that belongs to this guild.
on a scale of 1 to 10 how bad practice is it to try and make everything fit on single lines like this
is there any example to make a command using this
just use black👀
I'd opt for the second option without hesitation. I don't like to set a value to multiple variables in one line if the value is not always the same, it's a personal choice I guess.
server = bot.get_guild(id) or await bot.fetch_guild(id)
print(server.channels)
fetch_guild
it's physically painful to take up extra lines like that but it does seem a tiny bit more readable
get_ works too right?
black is fine for most stuff part which i don't really like is if i have parantheses in an equation they all get separated to one line each
im talking about the second option, get gets from cache and returns None if not found, fetch tries to actually get the object
ic
dont let it exceed 79 characters cause pep8
yes, people make fun of you
you summon the pep8 demon who puts random syntax errors in your code
ic so pep8 bad ❌ 😔
noone likes the horizontal scroll bar, do you
isn't it technically not exceeding 79 characters in both examples
PEP8's line length is kind of out of date, It was there so that everything fits in the screen but now we don't have low res monitors on that level
i make qqguild bot
People won't care if you break the 79 line length rule
Most of my projects are 120 or 90 line length anyways
i have a vertical monitor for my code and 79 characters is all that fits
ya and sometimes exceeding the limit makes code more readable
dont think black will touch any of them
Well probably because it's vertical
But line length is really negligible, hell just zoom out your buffer in whatever code editor
coding on a horizontal monitor is gross
what is the use of vertical monitor other than taking less desk space?
||totally not based||