#discord-bots
1 messages Β· Page 583 of 1
same error as last time
no
?
That is no error the statement just isn't true
neither in print statement nor output
debug the if
using debugger?
No
or adding print statement?
async def on_raw_reaction_add(payload):
print(f'Is it a bot? {payload.member.bot}')
k = True if payload.message_id in dict_of_colour_codes.values() else False
print(f'is message id in dict of colour codes? {k}')
if not payload.member.bot and payload.message_id in dict_of_colour_codes.values():
await curchannel.send('hey hey it works')
new_channel = await curchannel.guild.create_text_channel(name=f'ticket - {payload.member}')
if payload.channel_id == new_channel.id:
await curchannel.send('well done')
print("part 2 was triggered")
Run this.
What does it print?
how do i get the roles in a channel?
You mean from the server?
pff
?
Try channel.changed_roles
did curchannel send this message? await curchannel.send('hey hey it works')
What is curchannel?
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
first on top
Or just use OOP
enough OOP with java
why cant you just curchannel = message.channel?
great idea
is there some need of the variable in other functions
idk
An error keeps appearing even though Iβm handeling it π€
be specific about the error π€§
How can i make a message loop? i.e. ;
me: i!alw
bot: 123
bot: 123
bot: 123
bot: 123
bot: 123
....
Send a message in 5 sec
i mean , 'what error'
Itβs discord.errors.found
Iβll send the error
!d discord.ext.tasks.loop
discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
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/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 424, in defer
await adapter.create_interaction_response(
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
how can i get the role which was deleted or added when i am comparing before and after changed_roles in onguild channel update?
Use set or just -
whats the djboard command?
the error's related to it
help
and what about the perms that were updated for the preexisiting role ?
p r i n t, t h e, v a r i a b l e s
hmm

ah right thanks
You mean in the before/after event?
ye
!d discord.abc.GuildChannel
class discord.abc.GuildChannel```
An ABC that details the common operations on a Discord guild channel.
The following implement this ABC...
Discord.py 2.0 (rapptz)
I dont remember there being a custom id kwarg for views
i saw that
There is
Look at examples/views/persistent
Itβs on there
m
doesn't print this in output
and if i try to put that print statement out of that IF block i get referenced before assignment
p r i n t
t h e
v a r i a b l e s
You are putting a print statement inside a false if
it wont print ofc
Then why did you put it there?
What
referenced before assignment
Idk
π€¦ββοΈ
how do u know its false?
how can i fix it
any docs for music querys?
Playing music?
nope query system
Role Removed: {<Role id=841588561916854323 name='Moderator , no powers'>}
how can i get the role name from this?
removedrole = set(before.changed_roles).difference(set(after.changed_roles))
So a song list?
yes and play iy after the first song played automaticly
docs?
length*
lul
look at this
@bot.command(name='copy')
async def copyforme(ctx, *, message):
messages = ctx.message
if message == 'see':
await ctx.send(messages)
if message == None:
await ctx.send('You need to type something!')
await ctx.send('I will save this message to you. When you want to see your armazened messages, type: ``/copy see``.')
I want it to take the "message" argument and save it to the system. After that, when I type /copy see the bot sends the stored message but, idk how do i can do this. Anyone can help me?
help
access the attr of the object
wdym
database
The name of the role.
ey kayle u change discord.py to pycord?
Nope
uh diff people
using disnake atm
removedrole = set(before.changed_roles).difference(set(after.changed_roles)) embed = discord.Embed(description = f"**Channel Updated:** {after.mention}\n\nRole Removed: {removedrole}", color = discord.Colour.random(), timestamp = datetime.datetime.utcnow())
its a set so its gives error - set has no attr name
idk i was trying to get the role
owner = guild.get_member(637685929611493422)
AttributeError: 'NoneType' object has no attribute 'get_member'
code:
guild = bot.get_guild(894452684072046652)
owner = guild.get_member(637685929611493422)
what's the problem here
ErroR?
owner = guild.get_member(637685929611493422)
AttributeError: 'NoneType' object has no attribute 'get_member'
!e ```py
None.get_member()
@cloud dawn :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'NoneType' object has no attribute 'get_member'
I want a bot that when I send a message, it will add 3 reacts and when click on one it will dm me with the reaction I clicked
Good luck! I recommend using disnake.
Disnake?
!pypi disnake
and what is it
he's trying to see that guild is none
lol
guild = bot.get_guild(894452684072046652)
owner = guild.get_member(637685929611493422)
might be because 894452684072046652 isnt the guild id or something
Or it is just not in the cache
this is the guild identifier
!d discord.ext.commands.Bot.fetch_guild try this
await fetch_guild(guild_id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild") from an ID.
Note
Using this, you will **not** receive [`Guild.channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.channels "discord.Guild.channels"), [`Guild.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.members "discord.Guild.members"), [`Member.activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activity "discord.Member.activity") and [`Member.voice`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.voice "discord.Member.voice") per [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member").
Note
This method is an API call. For general usage, consider [`get_guild()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_guild "discord.ext.commands.Bot.get_guild") instead.
I recommend making your own function for this.
Or take the easy unpractical way of kayle
That is why i recommend your own function
this code is not in the function
its an a function isnt it
No your own get/ fetch function since the one of discord.py is very unpractical.
why make a function for something simple
@cloud dawn helpπ¦ , where do i print that print cmd?
I want to make these variables global
Like i said not in the false if statement
it doesnt work in IF, gives error outside if
gives error on the bottom
so that it can be used not only in one function
Yeah we don't use global for that
OOP or
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
Also print the payload channel
alright
does not exist?
Then look at the print and ask yourself why it isn't the same
only payload channel id
Yeah that one
ah ok
I still need them to be available in cog
or does doing so not work
self.guild = self.bot.get_guild(894452684072046652)
self.owner = self.guild.get_member(637685929611493422)
my error handling isnt working
I recommend starting off learning python first...
@commands.command()
async def wallet(self, ctx):
print("Test")
db = sqlite3.connect("database.db")
cursor = db.cursor()
print("Test")
cursor.execute("CREATE TABLE IF NOT EXISTS money(wallet_money INT, bank_money INT, member_id INT, guild_id INT)")
print("Test")
cursor.execute("SELECT * FROM money WHERE member_id = ? AND guild_id = ?", (ctx.author.id, ctx.author.guild.id))
wynik = cursor.fetchall()
if not wynik:
print("Test")
sql = "INSERT INTO money(wallet_money,bank_money,member_id,guild_id) VALUES(?,?,?,?)"
val = (100, 150, ctx.author.id, ctx.author.guild.id)
cursor.execute(sql, val)
print("Test")
print("Test")
embed = discord.Embed(
description=f"> :CORRECT: **β’ WALLET {ctx.author.name}**\n\n``Cash:``\n {wynik[0]}\n\n``Bank:\n``{wynik[1]}",
color=0xff8800,
)
print("Test")
embed.set_footer(
icon_url=ctx.author.avatar,
text=ctx.author,
)
print("Test")
await ctx.reply(embed=embed, mention_author=False)
db.commit()
cursor.close()
db.close()
Bot stop at
print("Test")
embed = discord.Embed(
description=f"> :CORRECT: **β’ WALLET {ctx.author.name}**\n\n``Cash:``\n {wynik[0]}\n\n``Bank:\n``{wynik[1]}",
color=0xff8800,
)
Logs:
Test
Test
Test
Test
Test
Test
Test
Test
finally
it's all current with discord, not python
There was no such thing where I taught
because it's a discord\
And whats wrong exactly
okay but where do i compare these?
where do i compare them
Well why is it false??
its not
They are not
Why does it print 3 times??

and second is when i react to original embed
i guess?
and third is when i react to new message in new channel
i am not sure about the second tho
π¦ help
create the db var outside the func
@commands.command()
async def leaderboard(self, ctx): #toplarΔ± gΓΆsterir
if (ctx.channel.id == bot_channel):
rankings = levelling.find().sort("xp",-1)
i = 1
embed = discord.Embed(title="Ranking:")
for x in rankings:
try:
temp = ctx.guild.get_member(x["id"])
tempxp = x["xp"]
embed.add_field(name=f"{i}: {temp.name}", value=f"Total XP: {tempxp}", inline=False)
i += 1
except:
pass
if i == 11:
break
await ctx.channel.send(embed=embed)
``` i have a leveling system with mongo db and i have this leaderboard command and its must show people who have the must exp and it only show Ranking: embed
i say its stop at embed
Bot stop at
print("Test")
embed = discord.Embed(
description=f"> :CORRECT: **β’ WALLET {ctx.author.name}**\n\n``Cash:``\n {wynik[0]}\n\n``Bank:\n``{wynik[1]}",
color=0xff8800,
)
@slate swan
You might want to remove that pass from your except statement. Never just pass all exceptions, because if you get an error you're not expecting, you don't see it.
Only catch exceptions that you want to ignore
Or handle
In that case he should print the exception
a = await ctx.reply(f'Added the role {role} to {member}!')``` How could I make it mention the role (right now it says the ID) and mention it without pinging the people that have it?
await ctx.reply(f"{role.mention}", allowed_mentions=AllowedMentions(roles=False))
!d discord.AllowedMentions
class discord.AllowedMentions(*, everyone=True, users=True, roles=True, replied_user=True)```
A class that represents what mentions are allowed in a message.
This class can be set during [`Client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Client "discord.Client") initialisation to apply to every message sent. It can also be applied on a per message basis via [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for more fine-grained control.
Ignoring exception in command meme:
Traceback (most recent call last):
File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/aarav/GitHub/awaffle_bot/main.py", line 88, in meme
subreddit=reddit.subreddit("memes")
KeyError: 'data'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/aarav/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 'data'```
async def meme(ctx):
subreddit=reddit.subreddit("memes")
all_subs=[]
top=subreddit.top(Limit=50)
for submission in top:
all_subs.append(submission)
random_sub=random.choice(all_subs)
name=random_sub.title
url=random_sub.title
em=discord.Embed(title=name)
em.set_image(url=url)
await ctx.send(embed=em)
how do i correct it?
I have a variable welcome
in it the text: Hello {member}, you are on the {guild} server.
Before the output there are variables member and guild and so when they are output they are written as plain text how to solve this
@bot.command()
async def lock(ctx):
ctx.guild.channels.set_permissions(ctx.guild.default_role, send_messages=False)
How to change the permission of all text channels ?
error:
Command raised an exception: AttributeError: 'list' object has no attribute 'set_permissions'
what i need put instead of += ? 281 line
Iterate through the channels list using a for loop.
!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.
async def callback(self, interaction: discord.Interaction):
assert self.view is not None
view: Menu = self.view
if self.values[0] == "Moderation":
self.view.variable += "Moderation"
self.menus[0].default = False
self.menus[1].default = True
await interaction.response.edit_message(embed=self.embeds2[self.embed_count], view=view)
elif self.values[0] == "Currency":
self.view.variable += "Currency"
self.menus[0].default = True
self.menus[1].default = False
await interaction.response.edit_message(embed=self.embeds[self.embed_count], view=view)
unsupported operand type(s) for +=: 'NoneType' and 'str'
what i need put instead of +=?
await member.add_roles(role)``` How can I make it to where it'll add the role `role`, but it's not adding it because it's an ID. So, I need to convert that ID to something somehow.
!d discord.Guild.get_role
get_role(role_id, /)```
Returns a role with the given ID.
It would be easier to just do create a discord.Object with the id and pass that
isn't this correct way to get a role from server? ```py
role = discord.utils.get(ctx.guild.roles, id=self.default)
self.default gives a role ID
you can just do bot.get_role
!d discord.Guild.get_role exists...
get_role(role_id, /)```
Returns a role with the given ID.
Thought so
Nothing like bot.get_role lol
sammmmmmmmmmmmmeeee thing
Just try it....?
so ctx.guild.get_role(id)
discord.utils.get is mainly for name kwarg
Show lol
@commands.command(aliases=["hush", "shh", "shhh"])
async def silence(self, ctx, time: int = None):
'''Silences the channel for default role'''
print(self.default)
role = ctx.guild.get_role(self.default)
if time is None:
time = 60 * 10
else:
time = time * 60
print(role.id)
...
``` ```print(role.id)
AttributeError: 'NoneType' object has no attribute 'id' ``` but the first print statement gave `776140379442905098`
and that is correct role id
Print role please
i just started using bot class
Any error?
when i type $begin
I restarted the bot and it's working π
nothing happens
Weird okay
weird but thx
any idea why?
What's items?
Because you have an on_message event set, that overwrites the default event (where the bot internally processes commands)
a long list of strings
Aaaah yes
You need to add process_commands to your on_message
Didn't see that
!d discord.ext.commands.Bot.process_commands
await process_commands(message)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageβs author is a bot and doesnβt call [`get_context()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Just change the deco to bot.listen()
which deco
@bot.event
both?
@commands.command()
async def generuj(self, ctx, role : discord.Role = None):
code = random_char(15)
db = sqlite3.connect("database.db")
cursor = db.cursor()
cursor.execute("INSERT INTO voucher(code, role_id) VALUES(?,?)", (code, role.id))
await ctx.send(f"Wygenerowano voucher na {role.mention}\nKod na nia to ``{code}``")
@commands.command()
async def odbierz(self, ctx, code):
db = sqlite3.connect("database.db")
cursor = db.cursor()
cursor.execute(f"SELECT code FROM voucher")
wynik=cursor.fetchall()
if wynik:
for kod in wynik:
if code == wynik:
await ctx.send("Odebrales wlasnie role!")
Insert into voucher dont working
i have 2
Yup
@commands.Cog.listener()
async def on_ready(self):
print("voucher.py - on")
cursor.execute("CREATE TABLE IF NOT EXISTS voucher(code STR, role_id INT)")
def random_char(y):
return ''.join(random.choice(string.ascii_letters) for x in range(y))
Random
cursor is undefined
oh i didn't see but
i have cursor.execute("CREATE TABLE IF NOT EXISTS voucher(code STR, role_id INT)") in command
and table is created
I have a problem in this code:
connect = False
@client.command()
async def play(ctx,url : str):
global connect
voiceChannel = discord.utils.get(ctx.guild.voice_channels,name='γ 1 γΨ£Ψ΅ΩΨ§Ψͺ')
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if not connect:
await voiceChannel.connect()
connect = True
@client.command()
async def leave(ctx):
global connect
voice = discord.utils.get(client.voice_clients, guild=ctx.guild)
if connect:
await voice.disconnect()
connect = False
else:
await ctx.send("the bot is not connected in voice Channel.")
he send this error in a terminal:
Ignoring exception in command play:
Traceback (most recent call last):
File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "C:\Users\hider\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: url is a required argument that is missing.
When I create role how can I make it second highest role in server? ```py
perms = discord.PermissionOverwrite(perm)
mutedrole = await ctx.guild.create_role(name="Muted", permissions=perms)
!d discord.Role.position
The position of the role. This number is usually positive. The bottom role has a position of 0.
Warning
Multiple roles can have the same position number. As a consequence of this, comparing via role position is prone to subtle bugs if checking for role hierarchy. The recommended and correct way to compare for roles in the hierarchy is using the comparison operators on the role objects themselves.
if I don't know amount of roles in server, it's kind of blind shooting.
Happens when you get a traceback
And why cmd? And not your ides shell
What are you using?
Why not in its console?
Doesnt pycharm have a console
how to send private messages to a user
Yea i think it does
Ls?
That's not how I wrote it
Hey i ama beginner to making bot. What is the video / web you can recommend
Beginner in python too or just dpy?
ls this is a private message
1st
Run the code in pycharms console
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Good way to learn
K
Yw
Yw meaning?
help
!d discord.Member.send
await send(content=None, *, tts=None, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, mention_author=None, view=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.9)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
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.
Did you even add its token???
client.run()
why is it indented so it is in the task
Has a error then
You have
[...].now()**..**now(timezone)
And I'm pretty suretimezoneis not defined, at least not in the part of code you shared
why two dots
Remove one dot
And define the timezone variable
You don't know what defining a variable means?
Have you learned Python before starting a bot?
Defining a variable is one of the first thing you learn
Interesting
x = "variable"
This is defining a variable...
Probably the first thing you learned, if you learned it
So you need to define the timezone
Or just remove the timezone part
And just use
now = datetime.datetime.now()
I can already tell you that the code is definitely not all right
hey i can't add channel into a category
what arg should i give to category?
name or id
anyone?
What is your code..
await ctx.guild.create_text_channel(name= i,category="shop", topic=k)
i is a string
k too
what should i set to category?
!d discord.Guild.create_text_channel
await create_text_channel(name, *, reason=None, category=None, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") for the guild.
Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/master/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.9)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/master/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/master/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
As you can see on the documentation, it requires a CategoryChannel object, and not a string
And you can get such an object using get_channel() or discord.utils.get()
Thanks
But get channel gives u channel object?
How do i get channel category object
Same way
Not only a channel object
!d discord.CategoryChannel
class discord.CategoryChannel```
Represents a Discord channel category.
These are useful to group channels to logical compartments.
x == y Checks if two channels are equal.
x != y Checks if two channels are not equal.
hash(x) Returns the categoryβs hash.
str(x) Returns the categoryβs name.
It returns a TextChannel, StageChannel, CategoryChannel, etc.
i have a question. I have heard discord.py will not be updated anymore?
is this true?
Yes
someone have a template code of a discord private dm bot?
It will not be updated anymore or it will not exist anymore?
import disnake, os, pymongo, datetime
os.system("pip install -U disnake")
from disanke.ext import commands
bot = commands.Bot(command_prefix=commands.when_mentioned_or("."), intents=disnake.Intents.all())
@bot.event
async def on_ready():
try:
os.system("cls")
print(f"Connected to client: {bot.user}")
except:
os.system("clear")
print(f"Connected to client: {bot.user}")
``` Error:
File "main.py", line 1, in <module>
import disnake, os, pymongo, datetime
ModuleNotFoundError: No module named 'disnake'```
Then when i take that out it says
No module named pymongo
it will exist, but no updated anymore
pip install it first
pip install disnake
im using replit, because my partner doesnt have vscode
Yay, it still exists.
At least I don't have to worry about upcoming updates.
shell exists in replit as well
Yh i just figured that out
I was wondering if anyone could help me, how would I get my bot object in a different file, I am trying to make a custom_checks.py file and I need to get the bot so I can get values, example bot.owner_id and so on, how would I do this?
File "beginner.py", line 7
async def ping(ctx):
^
SyntaxError: invalid syntax
for some reason this error pops up when i try to start my bot
i used the example from github btw
will anyone help me?
I added the time input and it works well but how would I make it say your timer has ended! (00hr:00m:00s)?
@commands.command()
async def timer(self, ctx, timeInput):
try:
try:
time = int(timeInput)
except:
convertTimeList = {'s':1, 'm':60, 'h':3600, 'd':86400, 'S':1, 'M':60, 'H':3600, 'D':86400}
time = int(timeInput[:-1]) * convertTimeList[timeInput[-1]]
if time > 86400:
await ctx.send("I can't do timers over a day long.")
return
if time <= 0:
await ctx.send("Timers don't go into negatives :/")
return
if time >= 3600:
message = await ctx.send(f"β±οΈ Remaining time: **{time//3600}hr:{time%3600//60}m:{time%60}s**")
elif time >= 60:
message = await ctx.send(f"β±οΈ Remaining time: **{time//60}m:{time%60}s**")
elif time < 60:
message = await ctx.send(f"β±οΈ Remaining time: **{time}s**")
while True:
try:
await asyncio.sleep(1)
time -= 1
if time >= 3600:
await message.edit(content=f"β±οΈ Remaining time: **{time//3600}hr:{time %3600//60}m:{time%60}s**")
elif time >= 60:
await message.edit(content=f"β±οΈ Remaining time: **{time//60}m:{time%60}s**")
elif time < 60:
await message.edit(content=f"β±οΈ Remaining time: **{time}s**")
if time <= 0:
await message.edit(content="β±οΈ Timer ended!")
await ctx.reply(f"Your countdown has ended! (**{timeInput}**)")
break
except:
break
except:
await ctx.send(f"Alright, first you gotta let me know how I'm gonna time **{timeInput}**...")
what's my problem here
@commands.Cog.listener()
async def on_member_join(self, member):
member = member.mention
guild = member.guild.name
membercount = member.guild.member_count
_id = member.guild.id
welcome = self.collection.find_one({"_id": _id})["welcome"]
if welcome == None:
pass
else:
embed = disnake.Embed (
title = f'ΠΡΠΈΠ²Π΅ΡΡΡΠ²ΡΠ΅Ρ **{guild}**:',
description = ">>> {welcome}".format(welcome=welcome).format(member=member, guild=guild, membercount=membercount),
colour = 0x694c5f
)
await member.send(embed = embed)
error
File "O:\Suzuki\cogs\settings.py", line 170, in on_member_join
guild = member.guild.name
AttributeError: 'str' object has no attribute 'guild'
Instead of your countdown has ended! (Time)?
Use python3
Code?
File "d:\Applications\mybot\bot.py", line 31, in <module>
@client.event()
TypeError: Client.event() missing 1 required positional argument: 'coro'```
Remove the brackets
how do i learn
Its always
client.event
And
client.command()
Learn what exactly
Do you know the python basics?
Yes
Try watching tutorials and use the api reference for any errors ig
are there any tutorials i could read
Learn how to code a Discord bot using Python and host it for free in the cloud using Repl.it.
π¨Note: At 16:43, Replit now has a new method for environment variables. Check the docs: https://docs.replit.com/programming-ide/storing-sensitive-information-environment-variables
Along the way, you will learn to use Repl.it's built-in database and cr...
Yeah hold up
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
And use the api reference for any errors or any other stuff like commands
Thanks guys
2 good tutorials you should watch
Np
This tutorial is very outdated and bad
^
Yes ik but just use the api reference to fix errors
you should not recommend this tutorial to beginners 
Never seen a up to date tutorial π€·ββοΈ
A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.
this one ^
Never seen it or done it so idk
how can i upload an image (without being embed)
!d discord.File
class discord.File(fp, filename=None, *, spoiler=False)```
A parameter object used for [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for sending file objects.
Note
File objects are single use and are not meant to be reused in multiple [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send")s.
send takes a file kwarg
how to insert a file here
embed.set_image(url= )
embed = discord.Embed()
embed.set_image(
url="attachment://filename.png"
)
image = discord.File("/path/to/filename.png")
await ctx.send(
embed=embed,
file=image
)```
it doesn 't work that 's how I wrote:
welcome_gif = random.choice(["welcome_1.gif", "welcome_2.gif", "welcome_3.gif", "welcome_4.gif", "welcome_5.gif", "welcome_6.gif", "welcome_7.gif", "welcome_8.gif", "welcome_9.gif", "welcome_10.gif"])
embed.set_image(url= f"attachment://{welcome_gif}")
image = disnake.File(f"resources/{welcome_gif}")
anyone good at py trying to help me fix this source code I keep getting an error this is an discord py bot btw
I'll pay u nitro or sum
no need for paying
everyone here will help for free
can you tell the code
and error, or what u wanna do with it?
anybody has a great tutorial on how to make a discord modmail? from scratch
error
Traceback (most recent call last):
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "O:\Suzuki\cogs\settings.py", line 196, in on_member_join
await member.send(embed = embed, file=image)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\abc.py", line 1414, in send
data = await state.http.send_files(
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\http.py", line 376, in request
raise HTTPException(response, data)
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').
ok thx
you didnt send the file
await member.send(embed = embed, file=image)
show full code
@commands.Cog.listener()
async def on_member_join(self, member):
user = member.mention
guild = member.guild.name
membercount = member.guild.member_count
_id = member.guild.id
welcome = self.collection.find_one({"_id": _id})["welcome"]
if welcome == None:
pass
else:
embed = disnake.Embed (
title = f'ΠΡΠΈΠ²Π΅ΡΡΡΠ²ΡΠ΅Ρ **{guild}**:',
description = ">>> {welcome}".format(welcome=welcome).format(user=user, guild=guild, membercount=membercount),
colour = 0x694c5f
)
embed.set_thumbnail(url= member.avatar)
welcome_gif = random.choice(["welcome_1.gif", "welcome_2.gif", "welcome_3.gif", "welcome_4.gif", "welcome_5.gif", "welcome_6.gif", "welcome_7.gif", "welcome_8.gif", "welcome_9.gif", "welcome_10.gif"])
embed.set_image(url= f"attachment://{welcome_gif}")
image = disnake.File(f"resources/{welcome_gif}")
await member.send(embed = embed, file=image)
Traceback (most recent call last):
File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 606, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 850, in exec_module
File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
File "C:\Users\felix\OneDrive\Desktop\1 new Prime\Asylum-src-main\cogs\HelpPaginated.py", line 12, in <module>
from discord_components import DiscordComponents, Button, ButtonStyle, InteractionType
ImportError: cannot import name 'InteractionType' from 'discord_components' (C:\Python39\lib\site-packages\discord_components\__init__.py)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\felix\OneDrive\Desktop\1 new Prime\Asylum-src-main\main.py", line 153, in <module>
client.load_extension(f'cogs.{filename[:-3]}')
File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 678, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Python39\lib\site-packages\discord\ext\commands\bot.py", line 609, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.HelpPaginated' raised an error: ImportError: cannot import name 'InteractionType' from 'discord_components' (C:\Python39\lib\site-packages\discord_components\__init__.py) ``` im trying to turn this py bot on and i keep getting errors
it's telling you that
the COGS you are trying to load is having error importing InterationType
@bot.command()
async def lock(ctx):
for channel in ctx.guild.channels:
try:
await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
except:
pass
Hi, I can't get the bot to interact with all the server channels
help me please
?
try removing
from discord_components import InteractionType
from cogs file
@slate swan
kk let me find the file and try that
Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "wl" is not found
@slate swan this right?
help @slate swan
You should use the client.command() decorator, not the client.event; since you're making a command.
how i can do it ?
> text
hi
where do i put it?
I was answering @slate swan.
thank you
Read this.
Can someone help
yes
try
idk the cmds
but it's telling python 2. something is found
u would need to get lastest py first
Are you trying to host your bot locally? That looks a lot like termux
now im getting this error
help me please
@slate swan did you check all the functions of cogs file?
i found this stuff on stackoverflow
it is- sending local image as embed in d.py
but you can customise it for sending other things
try it
file = discord.File("output.png")
e = discord.Embed()
e.set_image(url="attachment://output.png")
await ctx.send(file = file, embed=e)```
this is an error no one should come here with (indents)
check each function
and try
....and pip3
lol
elif not time:
await ctx.send("You must mention a time!")
else:
if not reason:
reason="No reason given"
try:
seconds = time[:-1]
duration = time[-1]
```yo what the
@bot.command()
async def lock(ctx):
for channel in ctx.guild.channels:
try:
await ctx.channel.set_permissions(ctx.guild.default_role, read_messages=True, send_messages=False)
except:
pass
Hi, I can't get the bot to interact with all the server channels
leave ctx in the line where you set the permissions
ctx.channel only refers to one channel (where you invoked the command)
install discord to python3.9
and it's not client.Bot, just client
pip3.9 install discord
wait that's probably not the command
python3.9 -m pip install discord.py
yes
then completely restart VS Code
I think so
nice
ignore_roles_as_roles = []
for role in ignore_roles:
i = message.guild.get_role(int(role[0]))
ignore_roles_as_roles.append(i)
print(ignore_roles_as_roles)```
Print:
```py
[<Role id=903714996188479499 name='Twitch'>]
[<Role id=903714996188479499 name='Twitch'>]```
why are the same roles appended even though they are two different ones (in the datebase)
https://cdn.discordapp.com/attachments/890585578465271851/906649239596195900/unknown.png
Is there a sleep command I can use in interactions because time.sleep and asyncio.sleep both throw errors
They work
But throws an error
Which I canβt handle
Send the error ur gttin
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 361, in _scheduled_task
await interaction.response.defer()
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\interactions.py", line 424, in defer
await adapter.create_interaction_response(
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\webhook\async_.py", line 189, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
i have debugged it to be time.sleep
thats causing it
Also cchrck ur token its invalid
Dont use time.sleep it will block ur code use asycio.sleep
thats what im using and its still throwing it
also are u responding to the interaction after wards?
@discord.ui.button(label='Play', style=discord.ButtonStyle.grey, emoji="\u25b6", custom_id="PLAYBUTTON")
async def play(self, button: discord.ui.Button, interaction: discord.Interaction):
if interaction.user.id == int(interaction.message.embeds[0].title.split('|')[1]):
message = await interaction.channel.send("playing! " + interaction.user.mention)
await asyncio.sleep(5)
await message.delete()
Use delete_after
await message.delete_after(5)
``` ?
No try adding it inside the message = await interaction.channel.send("playing! " + interaction.user.mention, delete_after=5)
nope py await interaction.channel.send("playing! " + interaction.user.mention, delete_after=5)
k thx
and to u too
there is dropdown in discord which is discord.ui.Select, what about the other one where options are in separate rows as buttons - what can I use to build this ui selection list?
discord.errors.InvalidArgument: file parameter must be File what is this error?
ignore_roles_as_roles = []
for role in ignore_roles:
i = message.guild.get_role(int(role[0]))
ignore_roles_as_roles.append(i)
print(ignore_roles_as_roles)```
Print:
```py
[<Role id=903714996188479499 name='Twitch'>]
[<Role id=903714996188479499 name='Twitch'>]```
why are the same roles appended even though they are two different ones (in the datebase)
https://cdn.discordapp.com/attachments/890585578465271851/906649239596195900/unknown.png
show code, but it means what it means; you've passed a file that aint a file
anyone can send add_role example?
Could someone help me, it won't allow me to make more than one embed command.
When I execute one command it works but the other embed doesn't.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game('What are you doing step jay'))
print('obama')
@client.event
async def on_message(message):
if message.content.startswith('.kade'):
embedVar = discord.Embed(title="Kade Engine Download", description="Downloads for Kade Engine 1.8", color=0x2C93FA)
embedVar.add_field(name="Kade Engine Installation", value="https://github.com/KadeDev/Kade-Engine/releases/tag/1.8", inline=False)
embedVar.add_field(name="Kade Engine Source (Recommended for Mod Makers)", value="https://github.com/KadeDev/Kade-Engine", inline=False)
await message.channel.send(embed=embedVar)
@client.event
async def on_message(message):
if message.content.startswith('.week'):
embedVar = discord.Embed(title="Kade Engine Download", description="Downloads for Kade Engine 1.8", color=0x2C93FA)
embedVar.add_field(name="Kade Engine Installation", value="https://github.com/KadeDev/Kade-Engine/releases/tag/1.8", inline=False)
embedVar.add_field(name="Kade Engine Source (Recommended for Mod Makers)", value="https://github.com/KadeDev/Kade-Engine", inline=False)
await message.channel.send(embed=embedVar)
client.run('TOKEN')
heres the code
dont use on_message for what your doing
use @quaint axle.command()
wdym
@client.command
async def week(ctx):
embedVar = discord.Embed(title="Kade Engine Download", description="Downloads for Kade Engine 1.8", color=0x2C93FA)
embedVar.add_field(name="Kade Engine Installation", value="https://github.com/KadeDev/Kade-Engine/releases/tag/1.8", inline=False)
embedVar.add_field(name="Kade Engine Source (Recommended for Mod Makers)", value="https://github.com/KadeDev/Kade-Engine", inline=False)
await ctx.channel.send(embed=embedVar)
like this?
\U0001f6d1: OCTAGONAL SIGN - π
Traceback (most recent call last):
File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 359, in _scheduled_task
await item.callback(interaction)
File "c:\Users\Harckepy\Desktop\Voice bot\voicebot.py", line 159, in quit
self.stop()
TypeError: 'Button' object is not callable```
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
I did a currency bot few years ago, what do you need help with?
Ok
Iβll send my code
You can modify it to your needs because my code was pretty dumb
It worked though(without databases)
@bot.command(aliases=["balance"])
async def bal(ctx, user: discord.Member = None):
with open("moneys.json", "r") as file:
balance = json.load(file)
if user is not None:
mention = user
image = user
if str(user.id) in balance:
print("user in dict")
else:
balance[str(user.id)] = 0
else:
mention = ctx.author
image = ctx.author
if str(ctx.author.id) in balance:
print("user in dict")
else:
balance[str(ctx.author.id)] = 0
with open("moneys.json", "w") as file:
json.dump(balance, file)
embed = discord.Embed(title=f"__account__", description="")
embed.set_author(name=mention, icon_url=mention.avatar_url)
embed.add_field(name="noice bucks", value=f":noice:: {balance[str(mention.id)]}")
await ctx.send(embed=embed)```
this was my balance code
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def add_money(ctx, user: discord.Member, amount: int):
with open("moneys.json", "r") as file:
balance = json.load(file)
if str(user.id) in balance:
balance[str(user.id)] += amount
else:
balance[str(user.id)] = amount
if amount == 1:
s = ""
else:
s = "s"
channel = bot.get_channel(769675445368258581)
embed = discord.Embed(title="money added", description=f"{amount} noicebuck{s} were added to {user.mention}'s balance")
await channel.send(embed=embed)
with open("moneys.json", "w") as file:
json.dump(balance, file)
await ctx.send(f"added {amount} noice buck{s} to {user.mention}'s balance")
``` add money command
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def remove_money(ctx, user: discord.Member, amount: int):
with open("moneys.json", "r") as file:
balance = json.load(file)
if amount == 1:
s = ""
else:
s = "s"
if str(user.id) in balance:
if amount > balance[str(user.id)]:
await ctx.send(f"cant remove noice bucks from {user.mention}, because {user.mention} would be in dept")
else:
balance[str(user.id)] -= amount
await ctx.send(f"removed {amount} noice buck{s} from {user.mention}'s account")
channel = bot.get_channel(769675445368258581)
embed = discord.Embed(title="money removed", description=f"{amount} noicebuck{s} were removed from {user.mention}'s balance")
await channel.send(embed=embed)
else:
balance[str(user.id)] = 0
await ctx.send(f"cant remove noice bucks from {user.mention}, because {user.mention} would be in dept")
with open("moneys.json", "w") as file:
json.dump(balance, file)
``` remove money command
@bot.command()
async def shop(ctx):
with open("shop.json", "r") as file:
shop = json.load(file)
embed = discord.Embed(title="shop", description="use !buy <item name> <amount(optional)>")
if not shop:
embed.add_field(name="shop empty", value="sorry, the shop is empty, wait for mods to add item")
await ctx.send(embed=embed)
return
else:
name = [x["name"] for x in shop.values()]
price = [x["price"] for x in shop.values()]
desc = [x["desc"] for x in shop.values()]
for x in range(0, len(shop)):
print(name)
embed.add_field(name=f":noice:{price[x]} - {name[x]}",
value=f"{desc[x]}")
await ctx.send(embed=embed)
``` shop command
@bot.command()
async def buy(ctx, item, amount : int = None):
with open("moneys.json", "r") as file:
balance = json.load(file)
with open ("shop.json", "r") as file:
shop = json.load(file)
with open("inv.json", "r") as file:
inv = json.load(file)
itemb = "item"
if item in shop:
if str(ctx.author.id) in balance:
if str(ctx.author.id) in inv:
pass
else:
inv[str(ctx.author.id)] = {}
if shop[str(item)]["price"] > balance[str(ctx.author.id)]:
await ctx.send(f"not enough money to buy {item}")
return
else:
if amount is not None:
if shop[str(item)]["price"] * amount > balance[str(ctx.author.id)]:
await ctx.send("not enough money to buy items")
return
else:
total = amount
else:
total = 1
balance[str(ctx.author.id)] -= shop[item]["price"] * total
price = shop[item]["price"]
if item in inv[str(ctx.author.id)]:
inv[str(ctx.author.id)][item] += total
else:
inv[str(ctx.author.id)][item] = total
await ctx.send(f"bought {total} {item} for {price * total} noice bucks")
else:
balance[str(ctx.author.id)] = 0
await ctx.send(f"not enough money to buy {item}")
else:
await ctx.send(f"cant find the item: {item}")
with open("moneys.json", "w") as file:
json.dump(balance, file)
with open("inv.json", "w") as file:
json.dump(inv, file)``` buy command
yes
this is the python discord srver
https://paste.pythondiscord.com/otozagamoq.sql inv command(it was a few characters long)
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def add_item(ctx, name, price : int, role : discord.Role = None, *, desc):
with open("shop.json", "r") as file:
shop = json.load(file)
if name in shop:
await ctx.send("item allready exists")
return
else:
shop[name] = {}
shop[name]["name"] = name
shop[name]["price"] = price
shop[name]["desc"] = desc
if role is not None:
shop[name]["role"] = str(role.id)
shop[name]["desc"] = "gives role " + role.mention + ". " + desc
rolem = "gives role " + role.mention + ". "
else:
shop[name]["desc"] = desc
rolem = ""
embed = discord.Embed(title="item created", description="")
embed.add_field(name=f":noice:{price} - {name}", value=f"{rolem}{desc}")
await ctx.send(embed=embed)
channel = bot.get_channel(769675445368258581)
await channel.send(embed=embed)
with open("shop.json", "w") as file:
json.dump(shop, file)
``` add item ciommand
yes
but the .json files are seperate
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def remove_item(ctx, name):
with open("shop.json", "r") as file:
shop = json.load(file)
if name in shop:
await ctx.send(f"{name} has been deleted")
embed = discord.Embed(title="item removed", description="")
embed.add_field(name=f":noice:{shop[name]['price']} - {shop[name]['name']}", value=f"{shop[name]['desc']}")
channel = bot.get_channel(769675445368258581)
await channel.send(embed=embed)
del shop[name]
else:
await ctx.send("item not found")
with open("shop.json", "w") as file:
json.dump(shop, file)
``` remove item command
@bot.command()
@commands.cooldown(1, 30, commands.BucketType.user)
async def gamble(ctx, amount : int):
with open("moneys.json", "r") as file:
balance = json.load(file)
if str(ctx.author.id) in balance:
pass
else:
balance[str(ctx.author.id)] = 0
if balance[str(ctx.author.id)] < amount:
message = await ctx.send("cant bet amount because balance is to low")
time.sleep(4)
await message.delete()
else:
balance[str(ctx.author.id)] -= amount
wa = random.randint(0, 10)
lotteryc = random.randint(0, 10000)
balance[str(ctx.author.id)] += amount * wa
if wa == 0:
message = await ctx.send("looks like you didnt win anything *sad trombone*")
time.sleep(4)
await message.delete()
else:
if wa == 1:
message = await ctx.send("you won your money back!!! woohooo!!")
time.sleep(4)
await message.delete()
else:
message = await ctx.send(f"you won {amount * wa} noicebucks!!! nice!!!")
time.sleep(4)
await message.delete()
if lotteryc == 69:
await ctx.send(f"{ctx.author.mention} YOU HAVE WON THE LOTTERY!!!!! OF 1000000000 NOICEBUCKS!!!")
balance[str(ctx.author.id)] += 1000000000
print(lotteryc)
with open("moneys.json", "w") as file:
json.dump(balance, file)
@gamble.error
async def gamble_error(ctx, error):
if isinstance(error, commands.errors.CommandOnCooldown):
await ctx.send(error)
else:
raise error
``` gamble command (with error handeling)
@bot.command()
async def use(ctx, item):
with open("inv.json", "r") as file:
inv = json.load(file)
with open("shop.json", "r") as file:
shop = json.load(file)
if str(ctx.author.id) in inv:
if item in inv[str(ctx.author.id)]:
if not shop[item]["role"]:
pass
else:
role = get(bot.get_guild(ctx.guild.id).roles, id=int(shop[item]["role"]))
await ctx.author.add_roles(role)
if inv[str(ctx.author.id)][item] > 1:
inv[str(ctx.author.id)][item] -= 1
await ctx.send(f"1 {item} used")
else:
del inv[str(ctx.author.id)][item]
await ctx.send(f"1 {item} used")
else:
await ctx.send("item not found")
else:
await ctx.send("item not found")
with open("inv.json", "w") as file:
json.dump(inv, file)``` use command
and thats all i had
plus some extra commands that arent important
a stats command warn command etc
for each json file just put {} in them
and the bot should work fine
@bot.command()
@commands.has_any_role("Staff", "harckepy himself")
async def stats(ctx, user: discord.Member = None):
with open("moneys.json", "r") as file:
balance = json.load(file)
with open("warns.json", "r") as file:
warns = json.load(file)
if user is not None:
userv = user
if str(user.id) in balance:
pass
else:
balance[str(user.id)] = 0
if str(user.id) in warns:
amountW = warns[str(user.id)]
else:
amountW = 0
else:
userv = ctx.author
if str(ctx.author.id) in balance:
pass
else:
balance[str(ctx.author.id)] = 0
if str(ctx.author.id) in warns:
amountW = warns[str(ctx.author.id)]
else:
amountW = 0
with open("moneys.json", "w") as file:
json.dump(balance, file)
sort = sorted(balance, key=balance.get, reverse=True)
embed=discord.Embed(title=f"__stats__", description="")
embed.set_author(name=userv, icon_url=userv.avatar_url)
embed.add_field(name="noice bucks", value=f":noice:: {balance[str(userv.id)]}")
embed.add_field(name="places on leaderboards", value=f"noicebucklb: placed {sort.index(str(userv.id)) + 1}")
embed.add_field(name="warns", value=f"{amountW}/3 warns")
embed.add_field(name="top role", value=f"{userv.top_role.mention}")
embed.set_thumbnail(url=userv.avatar_url)
await ctx.send(embed=embed)
this may not work so moify it a bit
you wont have the warn file
so the warn bit wont work
Wdym
I have a help command with the bot
If u want that
that has all the commands that i had o my bot
Itβs has the syntax, args and stuff
Thereβs no role in that ββ
You also need to dedent the @bot.command()
Pasting directly from discord may lead to some problems
So fix that before doing anything
Have you removed the indent block?
^ what he said
K sick
And remove Harckepy himself there and just add the roles you want to be able to run the command
I will throw an error if there is a role that isnβt in the server
Youβve removed a command and a decorator
How tf do u do that
Hey, I'm trying to get a wikipedia bot for my school discord server that can be able to respond to computer science and math questions primarily. The best I could do was a bot that could do math which isn't particularly helpful. Does anyone have source code for this purpose?
For doing math?
No not for doing math, that's easy. I'll post the one I made in a lil bit. For answering questions by posting stuff from wikipedia
so query?
like !question question
and it will answer uestion from wikipeida
If for example I asked. "Tell me what Computer Science is" Then I could get a result accordingly
Hi, I am trying to make a calculator bot, this is one command not finished, I am stuck on how to make await and outside function while including def check(msg1)
@client.command()
async def calc(ctx):
await ctx.send('What type of calculation do you want to do? **addition** > βͺ`add`β«, **subtraction** > βͺ`sub`β«, **division** > βͺ`div`β«, **multplication** > βͺ`mult`β«, **absolute value** > βͺ`abs`β«, **square root** > βͺ`sqr`β«, **squaring** > βͺ`sq`β«')
def check(msg):
return msg.author == ctx.author and msg.channel == ctx.channel and \
msg.content.lower() in ["add", "sub"]
msg = await client.wait_for("message", check=check)
if msg.content.lower() == 'add':
await ctx.send('What is your equation? Do π + *y* Only 2 numbers adding.')
def check(msg1):
ad = msg1.split(' ')
add = int(msg1[0])
addd = int(msg1[-1])
await ctx.send(add + addd)
import discord
from asyncio import sleep
import os
from discord.ext import commands
import random
import math
import keep_alive
from dotenv import load_dotenv
load_dotenv()
client = commands.AutoShardedBot(commands.when_mentioned_or('Please '))
@client.event
async def on_ready():
print('Ready.')
def Add(n: float, n2: float):
return n + n2
def sub(n: float, n2: float):
return n - n2
def rando(n: int, n2: int):
return random.randint(n, n2)
def div(n: float, n2: float):
return n / n2
def sqrt(n: float):
return math.sqrt(n)
def mult(n: float, n2: float):
return n * n2
@client.command()
async def add(ctx, x: float, y: float):
try:
result = Add(x, y)
await ctx.send(result)
except:
pass
@client.command()
async def subtract(ctx, x: float, y: float):
try:
result = sub(x, y)
await ctx.send(result)
except:
pass
@client.command()
async def Random(ctx, x: int, y: int):
try:
result = rando(x, y)
await ctx.send(result)
except:
pass
@client.command()
async def divide(ctx, x: float, y: float):
try:
result = div(x, y)
await ctx.send(result)
except:
pass
@client.command()
async def muliply(ctx, x: float, y: float):
try:
result = mult(x, y)
await ctx.send(result)
except:
pass
@client.command()
async def squareroot(ctx, x: float):
try:
result = sqrt(x)
await ctx.send(result)
except:
pass
keep_alive.keep_alive()
client.run(os.getenv('TOKEN'))
this just handles simple math problems
k
Pls add 2 2, and it adds them
ok
so i would use an on_message event and wikipedia api
getting the text between tell me what and is
and querying it through the api
heres the api link
sending wikipedia.summary("Wikipedia") should work
in @client.command(), mutliply is spelt wrong in async def
i need help
?
i have a disc bot but i want only me to use them how do i do that?
like !ban and kick
only for me
you cn do a check for roles, user or permissions
which one do you want to use?
check for roles
@commands.has_any_role("Role name")
``` add this below @native granite
oops
pinged someone
someone have a code of private dm bot?
yes
can u send in my dm pls
that it?
yes
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute
@bot.command()
@commands.dm_only()
async def dmtest(ctx):
await ctx.send("test")
thats a command that is used in dm
what does this mean
post full traceback :/
no but like I mean
Hey @slate swan!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Ignoring exception in command help:
Traceback (most recent call last):
File "main.py", line 224, in help
helpselect = msg[2]
IndexError: list index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 262, in help
await bot.say("/w help search\n/w help display\n/w help lang\n/w help random\n/w help about")
AttributeError: 'Bot' object has no attribute 'say'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'say'
Ignoring exception in command help:
Traceback (most recent call last):
File "main.py", line 227, in help
await bot.say("/w search 'term' - searches wikipedia on given term")
AttributeError: 'Bot' object has no attribute 'say'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 262, in help
await bot.say("/w help search\n/w help display\n/w help lang\n/w help random\n/w help about")
AttributeError: 'Bot' object has no attribute 'say'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'say
do i have the put the role name like the same caps?
did you just send in your bot in a public server
where anyone can troll u
good
@bot.command()
async def rps(ctx, msg):
print("s")
Rock = "R"
Sissors = "S"
Paper = "P"
list = 'Rock',"Sissors","Paper"
random_list = 1
list = "".join(random.sample(list,random_list))
print(list)
if msg == list:
await ctx.send("Draw")
elif 'Rock' == msg:
if list == 'Sissors':
await ctx.send("You win! Bot selected **Sissors**")
else:
await ctx.send("Losser")
elif msg == "Sissors":
if list == 'Paper':
await ctx.send("You win! Bot selected **Paper**")
else:
await ctx.send("Losser")
elif msg == "Paper":
if list == 'Rock':
await ctx.send("You win! Bot selected **Rock**")
else:
await ctx.send("Losser")
else:
print("nie dziala")```How to do when select choose such a word, for example
RoCk
Yh it's long isn't it :/
can u help me with one more thing
what am I doing wrong?
did you define commands.Bot/discord.Client as Client or client?
should be lowercase
also, add_reaction() should be awaited
if someone try a command and they dont have that role how can i make it so the bot ads a reaction
Hey I have a question, is it possible for discord to convert an argument into a numpy array directly? Or I have to convert the string?
import discord
from discord.ext import commands
import disgames
from disgames.mixins import Hangman
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
bot.add_cog(Hangman(bot))
error: Traceback (most recent call last): File "C:\Users\HiTech\Desktop\hhh.py", line 8, in <module> bot.add_cog(Hangman(bot)) File "C:\Users\HiTech\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 505, in add_cog raise TypeError('cogs must derive from Cog') TypeError: cogs must derive from Cog, the Hangman class is subclassed from commands.Cog tho ```py
import discord
from discord.ext import commands
class Hangman(commands.Cog):
"""
Hang man command
"""
def __init__(self, bot):
self.bot = bot
I am loosing my mind over this
Did you add bot.add_cog(Hangman(bot)) in your main bot file
if someone try a command and they dont have that role how can i make it so the bot ads a reaction
the top piece of code is the main file
in on_command_error you can do ctx.message.add_reaction which will ad reaction to the messagge which tried to invoke the command
Or just have a if statement that checks if they have the role and if they dont it adds it using add_roles
Thats probably better
Oh a reaction
Thought that was add role
im not saying theres an error but how do i make it so it reacts when they dont have the role
i think their question was involving the has_roles command decorater which checks if a person has a role or not and then allows them to use the command
if role not in member.roles will check if a role is not in someone's roles ig
any help please?
You can just do it the normal way and have bot.add_cog(Hangman(bot)) in the actual cog file and add it as a extension
I really dont know any other way
load_ext basically just imports the cog and executes the setup function, which is basically what i am doing
welp
but for some reason it seems to think that Hangman is not a cog
how do i make a ping command?
bot.latency returns the bot's ping in seconds, multiply it by 1000 to get the ping in milliseconds
how do i make an embed with all my commands?
bot.commands returns a list of every command your bot has
although if this is to make a help command i recommend you look into this https://gist.github.com/InterStella0/b78488fb28cadf279dfd3164b9f0cf96
how to use discord.ui.button? keeps telling me discord has no ui
You need to be using the master branch version of discord.py (from the github repo)
Using the pypi package will not work as its still on v1.7.3
You need v2.0.0a
Is it possible to be able to get the content of someoneβs status
@bot.command()
async def coinflip(ctx):
if random.choice(determine_flip) == 1:
myEmbed9 = discord.Embed(title="A COIN HAS BEEN FLIPPED!",
description = f"{ctx.author.mention} has got **Heads**!")
await ctx.send(embed=myEmbed9)
else:
myEmbed10 = discord.Embed(title="A COIN HAS BEEN FLIPPED!", d
description = f"{ctx.author.mention} flipped **Heads**")
await ctx.send(embed=myEmbed10)```
So I made a coin flip command
and everytime I do it I keep flipping heads
I've been spamming coinflip and it's not working
Stop misleading
Im just asking
@blissful crane your supposed to add that in your cog file not main file
Just ping me if someone knows what's wrong
Is my question too unclear?
read your embed description ,both of them says head lol
What old tutorial are you using
.say isnt an attribute anymore
that was from like 2016
................................
I'm so stupid
I really need some sleep
Thanks
Why does it say [pyflakes] local variable 'note' defined in enclosing scope on line 22 referenced before assignment in ```python
@client.command()
async def note(ctx, message=None):
note = (note[5:-1])
Can someone help?
@commands.command(name='createpoll', aliases=['poll'])
async def create_poll(self, ctx, question: str, *options):
if len(options) > 10:
await ctx.send("You can only supply a maximum of **10** options.")
else:
embed = discord.Embed(
title="New poll",
description=question,
color=ctx.author.color,
timestamp=datetime.utcnow()
)
embed.add_field(name="Options", value="\n".join([f"{numbers[idx]} {option}" for idx, option in enumerate(options)]), inline=False)
embed.set_footer(text="React to cast a vote!")
await ctx.send(embed=embed)
for emoji in numbers[:len(options)]:
await message.add_reaction(emoji)
message isn't defined
Show me an ss of line 22
last line of the one i put
How would I define it
using context
if it isnt working, try making a list and doing
await ctx.send(f'Result: \n{random.choice(Your_list)}')
it was already fixed
merely a typo
It works but thanks
Can you show me the full pyflake
ok
import discord
import random
import json
import requests
from discord.ext import commands
TOKEN = 'My token'
intents = discord.Intents.default()
client = discord.Client()
client = commands.Bot(command_prefix=".")
@client.event
async def on_ready():
await client.change_presence( activity=discord.Game('.help'))
print('Bot is ready.')
@client.command()
async def note(ctx, message=None):
note = (note[5:-1])
havent finished
Like this? await ctx.message.add_reaction(emoji)?
mm well you defined note in your function as note meaning the function or the variable idk but python doesnt like that try defining it outside the function
?
yes
Alr
I'm also having a similar issues with reaction emojis except I'm making an embedded buttons page and am having trouble checking the user's reaction
Here's how the embed page looks like
whats wrong?
I'm unable to get my bot the edit the page when I react with one of the added emojis
I tried checking the reaction emoji with reaction == [emoji] and user.reaction == [emoji] but it doesn't help
not edit a message
!d discord.Message.edit
await edit(content=..., embed=..., embeds=..., attachments=..., suppress=..., delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Unfortunately, that didn't work
can commands.Bot() take a list as a valid value for command_prefix?
yes
thanks
sure
TypeError: Iterable command_prefix or list returned from get_prefix must contain only strings, not list Cause I'm currently getting this when doing some stuff I probably shouldn't be doing with prefixes
replit is rigged
i cant import discord
are you using a function to get the prefix?
nah , when you return the value , add (client , message) to it
async def get_prefix(bot, message):
extras = await prefixes_for(message.guild) # returns a list
return commands.when_mentioned_or(*extras)(bot, message)
just an example
ah I'm not doing it that way
Much messier
owh what do you have?
in the end it boils down to
guild_prefs=cur.execute(f"SELECT prefixes FROM prefixes WHERE guild_id={message.guild.id}").fetchone()
if any([message.content.startswith(prefix) for prefix in guild_prefs]):
await bot.process_commands(message)
also realizing code is shit
hang on, I'm just retarder
so , in an on_message event?
give the embed a variable on await ctx.send, and then use that to add the reactions to that message
@commands.command()
async def hug(self, ctx, ):
response = requests.get("https://api.nekos.fun:8080/api/hug")
hug = response.json
embed=discord.Embed(title="Hug", color=0x109319)
embed.set_image(url=f"hug['image']")
embed.set_footer(text=f"Requested by {ctx.author.display_name}")
await ctx.send(embed=embed)
SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)
but yes in an event
what's the point of doing that , you dont need to check if message startswith the prefix or not if you use commands.Bot
on set image did you forget to format hug['image']?
what do you mean
Guild-specific prefixes
@bot.event
async def on_message(message):
if message.author.bot or message.guild==None:
return
await message.channel.send(cur.execute("SELECT * FROM prefixes").fetchall())
guilds=[int(pack[0]) for pack in all_packs]
await message.channel.send(f"GUILDS: {guilds}")
if message.guild.id not in guilds:
cur.execute(
f"INSERT INTO prefixes VALUES (?, ?)", (
message.guild.id, "['@copper leaf ', 'c!']"
)
)
await message.channel.send("Prefixes: "+str(cur.execute(f"SELECT prefixes FROM prefixes WHERE guild_id={message.guild.id}").fetchall()))
await bot.process_commands(message)
return
guild_prefs=cur.execute(f"SELECT prefixes FROM prefixes WHERE guild_id={message.guild.id}").fetchone()
# If the message starts with any of the guild's prefixes.
if any([message.content.startswith(prefix) for prefix in guild_prefs]):
await bot.process_commands(message)
``` ugly ik, don't mention it
its in an f string, so on set_image use {hug['image']}
ohh alright ima try that!
def get_prefix(bot , message):
prefix = connection.execute(your sql query blah).fetchone()
return prefix(bot , message)```
u tryna make guild prefixes?
i tried it and it makes the same error
send updated code please
does this happen on starting the bot?
when i use the command it happens
@commands.command()
async def hug(self, ctx, ):
response = requests.get("https://api.nekos.fun:8080/api/hug")
hug = response.json
embed=discord.Embed(title="Hug", color=0x109319)
embed.set_image(url=f"{hug['image']}")
embed.set_footer(text=f"Requested by {ctx.author.display_name}")
await ctx.send(embed=embed)
response.json() it mustbe
ima try that too
gl
doesnt work
error?
SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:997)')))
@commands.command()
async def hug(self, ctx, ):
response = requests.get("https://api.nekos.fun:8080/api/hug")
hug = response.json()
embed=discord.Embed(title="Hug", color=0x109319)
embed.set_image(url=f"{hug['image']}")
embed.set_footer(text=f"Requested by {ctx.author.display_name}")
await ctx.send(embed=embed)
oh wait
that space.
nah its not a ssl certificate issue
and dont forget the comma
and also if u use visual studio code in the bottom left you can change your version but if you started your bot fine then your prob using the right verision
im using idle
yes, idle 3.9.5 or something?
π
check what version ur on on idle shell
eh idle shell is fine
im lazy to download anything
the reason i dont use it is because pip keeps saying "oH dIsCorD nOt fOuNd"
same for me
lol
replit is online if you wanna use that
use pip3 π
ima check it
nah still doesnt work lol
wait what i use it
imagine haiving 4 versions of py installed
i do
my oldest one has to be 2.7
same , i mostly use only 3.8 or 3.9 tho
2.7 and 3.8 was preinstalled since i use linux
i used 3.1 and i kept wondering why my bot was not working even though i installed 3.9 π
and then i realized i had to change my version lmfao in the bottom left
how can i test to see if my bot is streaming? the strings im using clearly arent working and ive experimented with many including elif member.activity.type == ActivityType.streaming:
3.9 has some minor changes ig , its unable to load the cogs ryt?
bro wait 1 minute im researching how to check version because i never did i think π
i forgor
when you try to get the cogs from a folder
havent tried cogs in a while
python --version in your cmd.exe
python --version
3.10.0
:/
or it would be written on the top of idle
alr
3.10 is still not too perfect to work with everything
you called me nub π πͺ π π
i forgor when i did π
k but lets be a lil serious
alright im installing 3.9
3.9.8?
can u guys move to another channel or something cuz im trying to get some help for my discord bot which is literally the name of the channel. cant do that when its being filled by people having a dispute about which version of python they have installed.
cry about it haha!
jk jk
alr
how can i test to see if my bot is streaming? the strings im using clearly arent working and ive experimented with many including elif member.activity.type == ActivityType.streaming:
A βStreamingβ activity type.
i used copilot in my discord bot and when i tried doing a calculator command copilot just did "await ctx.send("RICKROLL LINK")"
is this compatible with v2?
Maybe the member needs to be actually streaming
why wouldn't it be
a lot of strings changed formating from things like . to _ and vise versa
possibly
Strings? you mean attributes?
yes
Otherwise you manually need to change the docs branch to master
yes
alright and another question
yes?
using premium_since is there any way i can dictate how long a user has been boosting a server for to coadherse it to its proper badge? something seemingly like "if boosting_for_1_month: boost = '
' , if boosting_for_6_months: boost = '
' "
Browser issue not related to dpy at all.
obviously formatted properly, but thats just to get the idea of what im after
An aware datetime object that specifies the date and time in UTC when the member used their βNitro boostβ on the guild, if available. This could be None.
well it returns a datetime object so yes you can do something like that
wouldnt that mean i have to apply each badge to a specific date?
im not very experienced with dt thats why im asking lol
You won't need to check for a specific date, you will just need to check the months part
if this is the case, id have to go back and modify each of the dates to -1 every day, otherwise it would be incorrect timing
how might i do this
I guess
I want to upload a file to
embed.set_image(url= )
```. but I did not try to get out like this:
```py
embed = disnake.Embed (
title = f'ΠΡΠΈΠ²Π΅ΡΡΡΠ²ΡΠ΅Ρ **{guild}**:',
description = ">>> {welcome}".format(welcome=welcome).format(user=user, guild=guild, membercount=membercount),
colour = 0x694c5f
)
embed.set_thumbnail(url= member.avatar)
welcome_gif = random.choice(["welcome_1.gif", "welcome_2.gif", "welcome_3.gif", "welcome_4.gif", "welcome_5.gif", "welcome_6.gif", "welcome_7.gif", "welcome_8.gif", "welcome_9.gif", "welcome_10.gif"])
image = disnake.File(f"resources/{welcome_gif}")
embed.set_image(url= f"attachment://{welcome_gif}")
await member.send(embed = embed, file=image)
Construct a datetime.timedelta object, pass in the days representing the months e.g 6months -> 182 ish days then add the timdelta object you just created to the premium_since datetime, and check if its equal or before datetime.datetime.now()
yikes
!d datetime.timedelta
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)```
All arguments are optional and default to `0`. Arguments may be integers or floats, and may be positive or negative.
Only *days*, *seconds* and *microseconds* are stored internally. Arguments are converted to those units...
there we go lol
did it send?
no
error
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\client.py", line 505, in _run_event
await coro(*args, **kwargs)
File "O:\Suzuki\cogs\settings.py", line 194, in on_member_join
await member.send(embed = embed, file=image)
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\abc.py", line 1414, in send
data = await state.http.send_files(
File "C:\Users\Baraban4ik\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\http.py", line 376, in request
raise HTTPException(response, data)
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.thumbnail.url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').
hm
?
booster1month = datetime.timedelta(days=30)
if member.premium_since == booster1month:
boost = ':1MonthBoost:'```
just write a for loop
could that work? im probably wrong
It wouldn't do what you want it to do
variable
For what
What do you mean
??
no no no i meant while loop
You need to construct the timedelta which you are doing, then you actually need to add it to premium_since and check if that is less than or equal to datetime.datetime.now()
OMGGGG
?
NOOOOO
bots bypass the ad system on youtube and a whole lot of other regulations
thats why groovy was shut down alongside many other music bots
YOUTUBE NOOOOO IM GONNA SUE YOTUTUBER\
ok fine lol, take a court case i guess, since u wanna be sarcastic about it
oh sorry emoji tos
alright thanks for the heads up
yw
realistically, youtube doesnt have authorization to see which user is trafficing their website, so if anything theyd have to go through discord, and discord doesnt release that sort of information, as long as youre not reported, youll be fine
for i in range (?)
???
objest oriented program?
ooh sorry this is not java
bye


java
like the snake
see
coffee

amin
iirc, discord has said bots should comply with the ToS from any services they use
And directly, in the Youtubes ToS it says not to bot them
Its not so much the "ad system" being bypassed
And realistically I doubt you'd be sued for a music bot, rather a C&D
true
That's what groovy got, and that's what got it shutdown
abba
Stop shitposting
help
please
why does this message not send to the channel
@client.command()
async def note(ctx, message=None):
await ctx.send('What place are you in?')
message = await client.wait_for("message")
await ctx.send("What topic is this note for.")
msg = await client.wait_for("message")
if message.lower() == 'place1' and msg.lower() == 'social':
channel = client.get_channel(channelid)
await channel.send(message)
else:
pass
You havenβt defined channelid anywhere
i meant the channel id is in there
cause i didnt want it to be public
Whatβs the error?
nothing, just doesnt send to the channel
You are trying to do .lower on a Message object
As the wait_for here returns a Message
You want to call lower on the content attribute of the message
^ message.content.lower() and msg.content.lower() respectively should work
ph
*oh
ill try
wow
<Message id={myidiwanttokeepprivate} channel=<TextChannel id=privateid name='bot-testing' position=6 nsfw=False news=False category_id=None> type=<MessageType.default: 0> author=<Member id=723041209098174554 name='Nutshell' discriminator='1239' bot=False nick='nutshell' guild=<Guild id=privateid name='servername' shard_id=None chunked=False member_count=154>> flags=<MessageFlags value=0>>
it gives this for some reason in the channel
Since youβre sending the message instead of the message.content
To access the content within the Message object itβd be [variable you set the message to].content
ok
wait what do you mean?
Instead of await ctx.send(message) youβll wanna do await ctx.send(message.content)
since message is an instance of discord.Message, so to get the actual content of the message you do message.content
!d discord.Message.content
The actual contents of the message.
help
please
@client.command()
async def note(ctx, message=None):
await ctx.send('What topic is it?')
message = await client.wait_for("message")
await ctx.send("What place is this note for.")
msg = await client.wait_for("message")
if message.content.lower() == 'test' and msg.content.lower() == 'wow':
channel = client.get_channel(mychannel_idi_keep_private)
await channel.message.content.send(message)
else:
pass
Not like that
learn how to differentiate classes and attributes
Meaning?
so like what?
i want to make the code fast
isnt discord.py already fast
i want to faster
i feel the code so slow
How?
Show me your command/code
there might be something blocking it and making it slow
What should i know before learning the discord.py
give me 5-10 mins
i want the bot to play music but it took 15 seconds to play the music
well see Danny's messages in discord.gg/dpy
you should learn the basics of python, OOP, asyncio or anything that relates to dpy really
are you using DiscordUtils to play the music?
Thank you guys
no!
what are you using then
