#discord-bots
1 messages · Page 940 of 1

that's what i'm saying
but okimii seems to disagree
imgur uses a subdomain to serve the images
it should still display bruh
no
Well after fixing the link, the sentence is not completely to read
it probably made it fit in
don't embeds have a max width
if you're making a typing test why not just have it send out the message in text
yeah of like 4 fields wide iirc
i had it before and then people just copy and pasted it and i can not put invisible Unicode character in it because it would not help
idk make it display in all upper case characters
and the answer only accepts lowercase
that way you can tell if they very quickly copy/pasted
what if you want the sentence to be returned capitalized
😔 the nickname
or is it possible to do if the user answered to fast it says something like "Dont you dare to copy and paste on me!"?
can sm1 send dpy's discord? cant seem to find it
well you can't just do that maybe the dude's typing 300wpm
You can measure time between wait_for
ty
how would you even calculate the typing speed?
!d discord.on_typing
discord.on_typing(channel, user, when)```
Called when someone begins typing a message.
The `channel` parameter can be a [`abc.Messageable`](https://discordpy.readthedocs.io/en/master/api.html#discord.abc.Messageable "discord.abc.Messageable") instance. Which could either be [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel"), [`GroupChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.GroupChannel "discord.GroupChannel"), or [`DMChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.DMChannel "discord.DMChannel").
If the `channel` is a [`TextChannel`](https://discordpy.readthedocs.io/en/master/api.html#discord.TextChannel "discord.TextChannel") then the `user` parameter is a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member"), otherwise it is a [`User`](https://discordpy.readthedocs.io/en/master/api.html#discord.User "discord.User").
This requires [`Intents.typing`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.typing "discord.Intents.typing") to be enabled.
i am new
as in WPM
Hi
won't be of use
because people don't type at a constant rate throughout a message
hi
Well that is the only way
i am beginner
yep
Pil might be a good way
U mean making a typeracer command? @tough lance
PIL if you want to create an image on the fly
I'm not the one making the command
just be careful on implementing it
I created a speed typing game xD
Yea typeracer
Even if you don't want to use PIL you can make a set of text on images and store in your local directory and just get any random of them when you want
Or use an API
how to start?
how to start what
Discord bot coding
..
Is that "coding" ?

Where did the prev one go
@slate swan :white_check_mark: Your eval job has completed with return code 0.
Drawing.....


Command:
@note.sub_command()
async def edit(inter: disnake.CommandInteraction, *, note_name : str ):
"Edit an existing note."
async with inter.bot.db.execute("SELECT name, content FROM notes WHERE name= ? AND user_id = ?", (note_name, inter.author.id,)) as cursor:
data = await cursor.fetchone()
if not data:
return await inter.response.send_message('A note with that name could not be found', ephemeral=True)
await inter.response.send_modal(modal=ExistingNote(inter.bot, note_name,data))
Modal:
class ExistingNote(disnake.ui.Modal):
def __init__(self, bot, user_input, pre_text) -> None:
self.bot = bot
self.use_input = user_input
self.pre_text = pre_text
components = [
disnake.ui.TextInput(
label="Note name",
placeholder="Enter note name here",
custom_id="name",
style=disnake.TextInputStyle.short,
max_length=100,
value=pre_text[0]
),
disnake.ui.TextInput(
label="Note content",
placeholder="Enter the contents of the note here",
custom_id="contents",
style=disnake.TextInputStyle.paragraph,
min_length=3,
max_length=1024,
value = self.pre_text[1]
),
]
super().__init__(title="Create note", custom_id="notebook", components=components)
async def callback(self, inter: disnake.ModalInteraction) -> None:
values = list(inter.text_values.values())
embed = Embed(description="The note has been saved!")
await self.bot.db.execute("UPDATE notes SET name = ? AND content = ? WHERE = name ? AND user_id = ?", (values[0], values[1], self.pre_text[0], inter.author.id,))
await self.bot.db.commit()
await inter.response.send_message(embed=embed, ephemeral=True)
And error
future: <Task finished name='disnake-ui-modal-dispatch-notebook' coro=<Modal._scheduled_task() done, defined at C:\Users\tenuk\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\modal.py:227> exception=NameError("name 'ctx' is not defined")>
Traceback (most recent call last):
File "C:\Users\tenuk\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\modal.py", line 229, in _scheduled_task
await self.callback(interaction)
File "c:\Users\tenuk\Desktop\Coding\feature changes apex\main.py", line 61, in callback
await self.bot.db.execute("UPDATE notes SET name = ? AND content = ? WHERE = name ? AND user_id = ?", (values[0], values[1], self.pre_text[0], inter.author.id,))
TypeError: 'coroutine' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\tenuk\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\modal.py", line 231, in _scheduled_task
await self.on_error(e, interaction)
File "c:\Users\tenuk\Desktop\Coding\feature changes apex\main.py", line 68, in on_error
print('Ignoring exception in command {}:'.format(ctx.command), file=sys.stderr)
NameError: name 'ctx' is not defined
C:\Users\tenuk\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py:1882: RuntimeWarning: coroutine 'InvokableApplicationCommand.__call__' was never awaited
handle = None # Needed to break cycles when an exception occurs.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
you didnt await something....its in the error
yes i know that
but what have i not awaited
Ctx is not defined ?
also ctx not defined
,<>
what's line 68? can u send the code
Many errors
Not sure if this is an outdated method for getting a guild object client.get_Guild(GUILDID) but I can't seem to find anything else for it
get_guild*
Lol
bruh
Another one
Is there any way to disable the logging done by disnake in the terminal?
okay updated code now this is the error ```py
Traceback (most recent call last):
File "C:\Users\tenuk\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\modal.py", line 229, in _scheduled_task
await self.callback(interaction)
File "c:\Users\tenuk\Desktop\Coding\feature changes apex\main.py", line 61, in callback
await self.bot.db.execute("UPDATE notes SET name = ? AND content = ? WHERE = name ? AND user_id = ?", (values[0], values[1], self.pre_text[0], inter.author.id,))
TypeError: 'coroutine' object is not subscriptable
C:\Users\tenuk\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ui\modal.py:231: RuntimeWarning: coroutine 'InvokableApplicationCommand.call' was never awaited
await self.on_error(e, interaction)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
!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.
finally
U get from google!
Any ideas?
u haven't awaited something in the modal
File "main.py", line 6, in <module>
g = client.get_guild(id, 507364684924452896)
TypeError: get_guild() takes 2 positional arguments but 3 were given``` Odd, not sure where it's getting 3 from
Nvmd
just pass in the id @spice adder
if flags.hypesquad_balance in user.public_flags:
embed.add_field(name=f"Badges", value=f":balance:", inline=False)```
It wont add the embed field..
Bruh u write the id
Seriously
what's the error
and what is flags
anything?
I don’t know how to make the warns not global, but different on each server, help me.
Sql
you could store the guild ids along
then whenever you query it, you could fetch allthe results and iterate through them
only if there is a better way
insert the warns.. then fetch it using select * from table_name
e1 = discord.Embed(
title="Ticket Tools Commands",
description="Here are the list of all the **Ticket Tool Commands** we have in Leaf's MM Service.\n\n `setup` `close` `delete` `rename` `transcript` `add` `remove` `mmban` `mmappeal`"
)
async def my_callback(interaction):
if select.values[0] == "Ticket Tools Commands":
await interaction.response.send_message(f"{e1}")
select.callback = my_callback
view = View()
view.add_item(select)
await ctx.send(embed=emb, view=view)```
insert into table_name with values..
@client.command()
async def syncofficials(ctx):
if ctx.author.id == 771252695667310623:
await ctx.send("Sorry")
else:
return
await ctx.send("Syncnorizing officials.")
for user in ctx.guild.members:
if ":tm:" in user.name:
role = ctx.guild.get_role(958411325082591272)
await user.add_roles(role)```
then use the select query
why its not working
thats how sql works, thats obvious
yeah
any errors?
no errors in the code and also in console
someone help me with this uh
can i have an example please?
await self.bot.db.execute("INSERT INTO warnlogs (guild_id, user_id, warns,) VALUES (?,?,?)", guild_id, user_id, reason)
data = await self.bot.db.fetchrow("SELECT * FROM warnlogs WHERE guild_id=? AND user_id=?", guild_id, user_id)
cursor.execute('CREATE TABLE IF NOT EXISTS warnings(id INTEGER PRIMARY KEY NOT NULL, warns INTEGER, guild_id INTEGER)')
this will create the table
res = cursor.execute('FROM warnings SELECT * where id = ? AND guild_id = ?', (member_id, guild_id)).fetchall()
#res will return a list of tuples```
Hm
@commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
await ctx.send('You are not in a voice channel.')
voice_channel=ctx.author.voice.channel
if ctx.voice_bot is None:
await voice_channel.connect()
else:
await ctx.voice_bot.move_to(voice_channel)
how do i fix this?
!d discord.Guild.voice_client
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
^
let's see what's here
Ashley the mvp frfr
!d discord.ext.commands.Context.voice_client
property voice_client```
A shortcut to [`Guild.voice_client`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild.voice_client "discord.Guild.voice_client"), if applicable.
I will just go away from here
no help them tf
you will
learn from your mistakes
nah you know your commands
i cant learn from my mistakes by not knowing the commands that are there
I'll just refrain myself from making an offensive joke now
offensive?
docs 🫂
if my hunch is correct jokes are not to be meant offensive or defensive or anything
jokes are jokes
well, this is python server
youre right
uhmm so i have this command that edit messages including the image but whenever i tried uploading a new image it won't work anymore
@client.command()
@commands.has_permissions(manage_guild=True)
async def edit(ctx, msg_id: int = None, channel: discord.TextChannel = None, *, message):
msg = await channel.fetch_message(msg_id)
await msg.edit(content=message)
if ctx.message.attachments:
await msg.edit(content=message, files=[await f.to_file() for f in ctx.message.attachments])
error
gnoring exception in command edit:
Traceback (most recent call last):
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "e:\Bots\Kornbep\main.py", line 35, in edit
await msg.edit(content=message, files=[await f.to_file() for f in ctx.message.attachments])
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\message.py", line 1111, in edit
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 156, in request
kwargs['data'] = utils.to_json(kwargs.pop('json'))
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\utils.py", line 328, in to_json
return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\gcpla\AppData\Local\Programs\Python\Python39\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type File is not JSON serializable
The above exception was the direct cause of the following exception:
How can i fix this i tried moving it up but it messed with my mention
so what i am saying is that when i put the " at the end it messes with my mention and puts it as a id
f is a discord.File already
you are closing the string before the curly brackets and you cannot mention in the title field and name field in embeds
how can i fix it
read it again
did you read what i siad i said i moved it behide value then this popped up
i dont need id i need mention
You cannot mention anything in the field title 😔
I just wrote that and got ignored
(That is what she said but u ignored her sooo 🤷)
so what do i do?
you can do @{member.name} but u won't get the blue mention box around it
so i cant fix it if i dont do that?
Its been ages since I have coded, don't
Well, you can see the result otherwise, yourself 🤷
can relate
Not sure you can have mentions in a field name like that
you can mention in the value or description fields
whats the issue
Nevermind, it’s been said already
ok
xenoren will change discord
Could just do str(message.author) 🤷♂️
😎
dont even need to stringify it
Sure
that is gonna return the username with the discrim
embed2.add_field(name="**Coach:**", value=f"{message.author.mention} ``{message.author}``")
this what i had last time
fails to understand
They don’t want a line break
I'll just leave
Well its gonna be difficult
how so
values cannot be multiline 🤷
tf you gonna change discord's src to do it?
i am just trying to firgure it out
......?
nvm
maybe #networks or #async-and-concurrency
okkk
Actually #web-development is a better place imho but everyone got different PoVs
line 397, in request
raise HTTPException(response, data)
disnake.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.options.1.emoji.name: Invalid emoji```
client = discord.Client()
g = client.get_guild(GUILDID)
@client.event
async def on_ready(g): #where g is a guild object
try:
bans = await g.bans()
banids = [banentry.user.id for banentry in bans]
f = open("banlist.txt", "a")
for id in banids:
f.write(str(id))
f.close()
except:
print("Something happened, probably no perms.")
TypeError: on_ready() missing 1 required positional argument : 'g'
remove the g
await ctx.send(embed=emb,
components = [
Select(
placeholder="Select the category you wish to view!",
options=[
SelectOption(
label ="Ticket Tools Commands",
value = "TTC",
description = "List of all the Ticket Commands in LMS.",
emoji = "🛠️"),
SelectOption(
label ="Roblox Commands",
value = "RC",
description = "List of all the roblox commands in LMS",
emoji = ":Roblox:")
]
)
]
)```
the :Roblox: emoji
oof
wrong name
idk about disnake
but if your bot has any mutual guild tht has that emoji
that will work @south jetty
but it isn't working
That is a thing for components too?
not sure.. but i suppose
same error but I used this
components = [
Select(
placeholder="Select the category you wish to view!",
options=[
SelectOption(
label ="Ticket Tools Commands",
value = "TTC",
description = "List of all the Ticket Commands in LMS.",
emoji = "🛠️"),
SelectOption(
label ="Roblox Commands",
value = "RC",
description = "List of all the roblox commands in LMS",
emoji = "🤖 ")
]
)
]```
wait.. it's saaying invalid emoji for the universal emojis too?
yes
ok fixed it
Command raised an exception: AttributeError: module 'disnake_components.client' has no attribute 'wait_for'
interaction = await client.wait_for("select_option", check=lambda i: i.component[0].value=="TTC")
await interaction.respond(content=f"{e1}")```
I dont think theres anything like that in my code
any1 can help me make my bot send private messages to a user
!d discord.Member.send ?
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
!e
while True:
print("test")
A = 'Username: Josh Password: 21358158319'
B = 'Username: Alex Password: wfajijg8ajfdw'
C = 'Username: Mario Password: 36537emgip'
Use_for = A or B or C
test = ''.join(random.sample(Use_for))
Error
TypeError: Random.sample() missing 1 required positional argument: 'k'
anyone can help?

could you add me as a friend? @slate swan
you use a listener to execute code whenever the specific event is triggered
you need the amount iirc
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.10)").
Example...
!d random.sample
random.sample(population, k, *, counts=None)```
Return a *k* length list of unique elements chosen from the population sequence or set. Used for random sampling without replacement.
Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).
Members of the population need not be [hashable](https://docs.python.org/3/glossary.html#term-hashable) or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.
I tried to install slash commands but when I try to run a cmd it isn't working?
what if theres no amount
then theres no sample
- which python library?
- does it have traceback? send it
the sample as shown here needs a length @hasty bison
no traceback I just installed pip install -U discord-py-slash-command
Guys how do I get bot DM the new joined people?
- Send code
You’re looking for the on_member_join event
And pair that with member.send
so it will be await member.send?
brb lemme try doing it
@client.event
async def on_member_join(member):
if member.guild.name == 'Los Angeles Roleplay Community': #type your server name
await member.send(f'Hey {member.mention}! Welcome to **{member.guild.name}** We wish you a warm welcome! :D\n\If you have any questions, feel free to ask one of our Staff Team Members! We would be more than happy to assist you!')
Like this? @slim ibex
And should I add like a break? How to.
I don't want it to spam.
@sick birch
My discord bot requires Python v4 but I can't find a docker for it, anyone has one?
damn you already got python 4.0?
thats crazy im still on 3.10
oh it hasnt released
It’s tedious because as your bot gets larger, you will be adding a check for each guild name
ERROR: Could not find a version that satisfies the requirement discord_slash (from versions: none)
ERROR: No matching distribution found for discord_slash
HElp :(
You can use a database to circumvent that
ofc it hasnt released were still on 3.10💀
There is no Python v4.x
ye sorry
but anyne help:
ERROR: Could not find a version that satisfies the requirement discord_slash (from versions: none)
ERROR: No matching distribution found for discord_slash
why even download the lib
^
just use main
oh sry
@bot.command(name="start")
async def start(ctx):
guild = ctx.guild
admin_role = guild.get_role(945847161596297277)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
admin_role: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True)
}
channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)
await channel1.send("Hi! for help on how to order, do !help", mention_author=True)
await ctx.message.delete()
'NoneType' object has no attribute 'id'. i havent changed anything, why is this happening?
show full tb
i don't seem to find id attribute being used in that codeblock anywhere.. im blind or wot?
Hello guys, how would I go about deleting a channel if an author of the channel doesn't respond in a certain time?
Making a ticket system and though it would be a nice feature to have.
!d discord.TextChannel.delete
await delete(*, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/master/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to use this.
It's a Private Bot, lol.
IK THATS WHAT IM SAYING
yeah I know how to delete the channel, but don't know how to delete it if a user doesn't respond in X time.
but thanks nonetheless!
@slim ibex Is this good tho? Do I need to add like break command? I don't want it to spam people's DMs
@client.event
async def on_member_join(member):
if member.guild.name == 'Los Angeles Roleplay Community': #type your server name
await member.send(f'Hey {member.mention}! Welcome to **{member.guild.name}** We wish you a warm welcome! :D\n\If you have any questions, feel free to ask one of our Staff Team Members! We would be more than happy to assist you!')
Help?
Ignoring exception in command start:
Traceback (most recent call last):
File "C:\Users\trent\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\trent\Desktop\DiscordBot\discordbot.py", line 144, in start
channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)
File "C:\Users\trent\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 948, in create_text_channel
data = await self._create_channel(name, overwrites, ChannelType.text, category, reason=reason, **options)
File "C:\Users\trent\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\guild.py", line 844, in _create_channel
'id': target.id
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\trent\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\trent\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\trent\AppData\Local\Programs\Python\Python310\lib\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: 'NoneType' object has no attribute 'id'
OKK BROO I GOT IT AT LEAST I'M NOT BLINDD
demm
Anybody lol
just wait for a message with wait for and add a timeout
Aaah ok
I'd use ID instead of name
and you can just catch a asyncio.TimeoutError and just delete the channel
Thank you very much :) @slate swan
target is None
How to fix it?
e1 = discord.Embed(
title="Ticket Tools Commands",
description="Here are the list of all the **Ticket Tool Commands** we have in Leaf's MM Service.\n\n `setup` `close` `delete` `rename` `transcript` `add` `remove` `mmban` `mmappeal`",
color = 0x5dff00)
async def my_callback(interaction):
await interaction.response.send_message(f"{e1}")
select.callback = my_callback
view = View()
view.add_item(select)```
Why is it showing this and not the embed
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/client.py", line 440, in sync_all_commands
existing_cmds = await self.req.get_all_commands(guild_id=scope)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
install it
you need permissions
youre trying to send the object you need to set it to the embed kwarg
It has admin role
it is not installed
embed kwarg?
then thats why the error raises
How do I give it that
the author part?
channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)
below you see how theirs an embed kwarg
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=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.10)") 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.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
wut
doesn't want to install
How do I give bot permission in dev portal
OH, ok I remember now silly me

wdym
@slate swan would you mind taking over for me in trying to learn flask
i dont understand what target is none, mind explaining more?
No idea, I’m getting missing Access and okimii said I need to add permission in portal

Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/client.py", line 440, in sync_all_commands
existing_cmds = await self.req.get_all_commands(guild_id=scope)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
pyinstaller not installing
Is there a bot command/tga here on why not to host on replit
how
.
i know
async def my_callback(interaction):
await interaction.response.send_message(embed = e1)
select.callback = my_callback
view = View()
view.add_item(select)
await ctx.send(embed=emb, view=view)```
How can I make it so it can only respond to one of the option because it is responding to other options with the same embed
@slate swan
I’ve had error over error because of me trying to add Slash Commands
its pinned
Hi, anyone knows why @bot.on_ready would take like 3 minutes to execute
it gets triggered on cache population and i doubt it would trigger that slowly do you have anything blocking?
nicely done binds
Can anyone help me with this
what could be blocking it
idk request time.sleep and other sync stuff
break keyword cannot be used outside of loops so it would be a syntax error if you used it in just an if statement
how big is ur bot?
I forgor 💀
!d break
7.9. The break statement
break_stmt ::= "break"
``` [`break`](https://docs.python.org/3/reference/simple_stmts.html#break) may only occur syntactically nested in a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) or [`while`](https://docs.python.org/3/reference/compound_stmts.html#while) loop, but not nested in a function or class definition within that loop.
It terminates the nearest enclosing loop, skipping the optional `else` clause if the loop has one.
If a [`for`](https://docs.python.org/3/reference/compound_stmts.html#for) loop is terminated by [`break`](https://docs.python.org/3/reference/simple_stmts.html#break), the loop control target keeps its current value...

small x)
go lang = bad
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord_slash/client.py", line 440, in sync_all_commands
existing_cmds = await self.req.get_all_commands(guild_id=scope)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 248, in request
raise Forbidden(r, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
I install pyinstaller and it says "module not found"
I don’t think so, how do I do that
I have a seperate class that loads before the bot with db conenction and simple stuff
it was like that for me once due to slow internet 💀
that doesnt depend on internet connection
u using any synchronous lib?
thanks
OwO
!d discord.on_connect is when it connects to the gateway
discord.on_connect()```
Called when the client has successfully connected to Discord. This is not the same as the client being fully prepared, see [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") for that.
The warnings on [`on_ready()`](https://discordpy.readthedocs.io/en/master/api.html#discord.on_ready "discord.on_ready") also apply.
mariadb, random, time - for uptime, json and math
time for? sleep?
Alright
no no asyncio.sleep for timeouts
alr
i will try on_connect (to get what i need) maybe it'll load faster x)
it does load faster as the bot connects to the gateway fairly quickly
i m playing with selfbots i know it s against tos but i m lazy and some simple comamnds won t hurt anyone
still against tos and we dont talk about self bots here
roger that
whats a self bot?
wont mention em again
an automated user account
oh
I have other bots but but yeah dn why i wanted one of thsoe
Help please
yo
AttributeError: 'Guild' object has no attribute 'member
server_bot = bot.get_guild(server)
await ctx.send(server_bot)
for member in server_bot.members:
print(server_bot.member)```
any ideas?
Error kind of says it all
Maybe you meant members, plural
async def my_callback(interaction):
await interaction.response.send_message(embed = e1)
select.callback = my_callback
view = View()
view.add_item(select)
await ctx.send(embed=emb, view=view)```
How can I make it so it can only respond to one of the option because it is responding to other options with the same embed
can someone pleas help me
If you only want it to respond to one option why include others
what do you mean?
@bot.command()
async def message(ctx, server:int):
server_bot = bot.get_guild(server)
for member in server_bot.members:
if member == ctx.author:
pass
else:
print(member)```
Im trying to get the memebrs in a server
but like it only gets itself
for some reason
you just need to use ctx.guild.members
The shell exited because something occurred that was unexpected
status 127 means the command wasn’t found
@bot.command(name="start")
async def start(ctx):
guild = ctx.guild
admin_role = guild.get_role(945847161596297277)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
admin_role: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True)
}
channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)
await channel1.send("Hi! for help on how to order, do !help", mention_author=True)
await ctx.message.delete()
'NoneType' object has no attribute 'id' for : channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)
there is no nonetype
The error is in that line?
I don’t really have time to help with this rn tbh. Hopefully someone else comes around soon 🗿
send it
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
What does print(ctx.guild) return?
just make it run that?
@bot.command(name="start")
async def start(ctx):
guild = ctx.guild
print(guild)
Can you send the screenshot of the error?
how would i do that, soory?
commendt out the overwrites {}
ahhh
and remove the overwrite kwarg from text_channel
Let's see if it creates the text channel without it
now the overwites in channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites) is undefined
remove the overwrites=overwrites
one of the keys in your overwrite dict is probably None
Mhm
it works @tidal hawk
yeah the problem was in overwrites
can someone please just help me with this
Yeah, but atm other people see the channel
could be that your id didnt match any role
Lmao - laughing my ass off
BRUHH
Happens to best of us
hey, please avoid using ableist language here
shit sorry
xD
no worries
ableism.. new word added to my dictionary
I didn’t know what that meant either until that same mod warned me for the same reason as that guy just now
Something new everyday
Can someone help me with an error response?
@bot.slash_command(description="Search the Overwatch database and retrive base profile statistics.")
async def profile(interaction : Interaction, battle_net : str = SlashOption(description="Example: (CameronBryce#11490) Replace '#' With The '-' Symbol.")):
async with aiohttp.ClientSession() as session:
response = await (await session.get(f"https://owapi.io/profile/pc/us/{battle_net}")).json()
#print(response)
How might I edit this to send an embed if they type the wrong username?
If someone types an incorrect username, it comes back as this in my console -
29.03 20:39:32 [Bot] valueB = "Username: `" + str(response["username"]) + "`\\n" 29.03 20:39:32 [Bot] KeyError: 'username'
I've tried a try and except but it didn't seem to work, might have done it wrong.
Right, I just did it wrong lol
Send the snippet how you did it
kinda useless
Try:
@bot.slash_command(description="Search the Overwatch database and retrive base profile statistics.")
async def profile(interaction : Interaction, battle_net : str = SlashOption(description="Example: (CameronBryce#11490) Replace '#' With The '-' Symbol.")):
async with aiohttp.ClientSession() as session:
response = await (await session.get(f"https://owapi.io/profile/pc/us/{battle_net}")).json()
#print(response)
Except:
Print("False")
That's what I did before, someone said to do it that way
you could just use dict.get() to get a value and if it doesnt exist it just returns None
@bot.slash_command(description="Search the Overwatch database and retrive base profile statistics.")
async def profile(interaction : Interaction, battle_net : str = SlashOption(description="Example: (CameronBryce#11490) Replace '#' With The '-' Symbol.")):
async with aiohttp.ClientSession() as session:
try:
response = await (await session.get(f"https://owapi.io/profile/pc/us/{battle_net}")).json()
#print(response)'
except KeyError:
print('error')
I'd be interested in trying that way but I've just never heard of that way so far.
Can you explain how if it's better?
Thank you
!d dict.get
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "KeyError").
does anyone know node.js?
Who is node js
I'll check into that too 🙂
It worked, thank you
You're welcome :)
and yeah.. check out the dict.get, it's more cleaner way
Will do, I'm still newish, just trying to get the basics. Recently found out aiohttp makes my code 100x faster than requests for example,
Work in progress (:
not really
you can get node.JS help in #web-development. I know some node though
its just async lmao
Oh, it took it 20s before, then it only took like .5s after
I just assumed it's faster
Might be my bad code
is there anywhere i could ask for somebody to try and break my bot? i want to stress test it for any exploits
useless server
If people don't know the answer here, go to the help section.
wait could i add a cooldown to the cmds
@bot.command(name="start")
async def start(ctx):
guild = ctx.guild
admin_role = guild.get_role(958175222744367134)
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True),
admin_role: discord.PermissionOverwrite(view_channel=True),
guild.me: discord.PermissionOverwrite(view_channel=True)
}
channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)
await channel1.send("Hi! for help on how to order, do !help", mention_author=True)
await ctx.message.delete()
and
@bot.command(name = 'order')
async def order(ctx: commands.Context, *, echo: str) -> None:
emb=discord.Embed(title="Confirm with ✅. Retry with ❌ ",description=echo)
msg = await ctx.send(embed= emb)
await msg.add_reaction("✅")
await msg.add_reaction("❌")
await ctx.message.delete()
def check(reaction, user, ):
return user == ctx.author and str(reaction.emoji) in {'✅', '❌'}
try:
reaction, user = await bot.wait_for('reaction_add', check=check)
except asyncio.TimeoutError:
channel = ctx.channel
await channel.send('you timed out...')
return
if str(reaction.emoji) == '✅':
channel = ctx.channel
await channel.send('***Gotcha! Order confirmed! Unless your order is rejected, you will not receave any other messages until delivery/check-in! PLEASE! __KEEP NOTIFICATIONS ON!__***')
channel2 = bot.get_channel(954898254783459388)
await channel2.send(f"<@{user_id}> \n {echo} ")
A runtime for JavaScript allowing it to run on the server
- User can keep spamming the start command, which results tons of channels and 2. There is no timeout and no feedback for ❌
I was playing around
i asked if i can add a cooldown 🗿
but ik
Yes you can 🗿
ok that seems easy enough, can i add a msg to say like : oops rthis is on cooldown
yep
i need some help
@client.command(aliases=["av"]) # i will be adding this
async def avatar(ctx, member: discord.Member=None):
if member is None:
member = ctx.author # ok wait im gonna do 2 and you cacn pick
req = await client.http.request(discord.http.Route("GET", f"/users/{member.id}"))
avatar_id = req["avatar"]
embed=discord.Embed(color=color.color, description=f"`{member.name}'s avatar`\n [png](https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.png?size=1024) , [jpg](https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.jpg?size=1024)")
embed.set_image(url = member.avatar)
await ctx.reply(embed=embed, mention_author=False)
self.add_item(discord.ui.Button(label='png', url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.png?size=1024"))
self.add_item(discord.ui.Button(label='jpg', url=f"https://cdn.discordapp.com/avatars/{member.id}/{avatar_id}.jpg?size=1024"))
How come this await is being underlined red?
def SetChannel(value):
overwrites = submissionChannelID.overwrites
overwrites[guild.default_role].send_messages = value
await submissionChannelID.edit(overwrites=overwrites)```
Can I not edit channels using the bot in regular functions?
Oh is it cause I left out the
@client.event and async?
Rip, PascalCase
await can only be used in an asynchronous func lol. Why would you want it outside?
whats wrong with pascal and what do you mean outside?
Pascal is only used for class names
If I dont include await the bot wont edit the channel
what case should I use then for functions?
Yes, which needs to be inside a function defined as asynchronous
snake_case
Thats why you see on_message instead of OnMessage
ah ok
well now Ive ran into another problem
async def set_channel(value):
overwrites = submissionChannelID.overwrites
overwrites[guild.default_role].send_messages = value
await submissionChannelID.edit(overwrites=overwrites)
def time_check():
while True:
time.sleep(1)
currentTime = time.ctime()
if "Sun" in currentTime:
set_channel(False)
print("its sunday!!")
elif "Mon" in currentTime:
set_channel(True)
print("its monday!!")
else:
set_channel(False)
print("not monday or sunday")```
the time_check wants the set_channel calls to be awaited
and if I make it async and await them then this wants the time_check func to be awaited as well
if __name__ == "__main__":
Process(target=time_check).start()
client.run(botToken)```
and idk how im supposed to await this
is there a way to check the date in audit logs?
Please check the docs before asking a question https://discordpy.readthedocs.io/en/stable/api.html#audit-log-data
oh ma bad g i asked cuz i didnt find it
Theres a tab on the left that lists everything in the bot pretty much
i found it dw
its created_at
👍

how tf is the emb = line indented wrong?
@bot.command(name = 'order')
async def order(ctx: commands.Context, *, echo: str) -> None:
@commands.cooldown(2, 150, commands.BucketType.user)
emb=discord.Embed(title="Confirm with ✅. Retry with ❌ ",description=echo)
msg = await ctx.send(embed=emb)
await msg.add_reaction("✅")
await msg.add_reaction("❌")
await ctx.message.delete()
Why is your cooldown decorator inside a function
It's supposed to decorate a function
i believe that @commands.cooldown(2, 150, commands.BucketType.user) should be outside the function
^
🤦♂️
Any reason why my output of my embed starts off in white text and then goes grey?py await interaction.channel.send(content=f"``json\n{embed.to_dict()}``")
json syntax highlighting
Doesn't look like valid json
// is a comment iirc
yeah iirc comments in js are //
well the embed is produced by thispy async def info_func(interaction, member): member_status = "No status" if member.activity is None else member.activity.name embed = Embed(title = f"{member}", description = f"Status: **{member.status}**\n*{member_status}*", colour = member.colour) embed.set_author(name = f"{member.id}", icon_url = member.avatar.url) embed.set_thumbnail(url = member.avatar.url) await timestamps_func(member, embed, True) roles = [f"{role.mention}" for role in member.roles] if len(roles) == 0: roles.append("No roles") has_key = [perm for perm in bot_var.config.key_perms if getattr(member.guild_permissions, perm)] if len(has_key) == 0: has_key.append('No permissions') embed.add_field(name = f"Roles: {len(roles)}",value = f"{len(roles)} roles" if len(" ".join(roles)) > 1000 else " ".join(roles), inline = False) embed.add_field(name =f'Key permissions', value = ", ".join(has_key).replace("_"," ").title(), inline = False) await interaction.response.send_message(embed=embed) return embed
They are
yeah
so does Embed.to_dict produce json in python dict format? I'm trying to work out how I can build a embed from a dict by looking at how my current embeds are built
if you are making an mutable variable
thats right
variables declared with let are mutable
var is usually not recommended
but if you're running something like babel or tsc it'll use var to support older browsers
^
Check out the discord api docs for embed json structure
i have done, can't find any examples on their site but I did find a link to a AutoCode page which has a embed builder
yeah that could help
https://discord.com/developers/docs/resources/channel#embed-object this has all the fields
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
You want like the raw api dict right?
they want to use a raw dict to construct an embed
Doesn't to_dict give an example
in dpy's docs, nope https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed.to_dict
No i meant give an example in terms of when you use this on an embed object in your code.
That is what I was referring to when I gave you the method.
I don't really get why you'd want to use a raw dict though
like this?json { 'thumbnail': { 'url': 'https://cdn.discordapp.com/avatars/884558598401818634/add5ead50d6e0f5db38e63524608e4a9.png?size=1024' }, 'author': { 'name': '884558598401818634', 'icon_url': 'https://cdn.discordapp.com/avatars/884558598401818634/add5ead50d6e0f5db38e63524608e4a9.png?size=1024' }, 'fields': [ { 'inline': True, 'name': 'Joined Server:', 'value': '<t:1630965996:R>' } ], 'color': 3066993, 'type': 'rich', 'description': 'Status: **offline**\n*No status*', 'title': 'Kuhale Support#1957' }I've been told that json can't have // (as it thinks it's a comment) so I'm not sure what's going on with the links
It is easier when creating a command.
for embeds?
I'm making a embed builder using those new pop out forms, I think they're called modals but i'm not sure, and then the embed builder stores the embed dict in the db for later use
it made more sense to store the straight dict/json rather than making a table row for each possible part of a embed (like no point having 25 columns for fields if you only use 2)
the modal will have a section for each part of the embed (title, fields, etc) and then I take those modal responses, construct a dict from them and store that dict.
I'm also going to make a dashboard which includes a embed builder, and it seemed a good idea to make that return a dict
Well yeah like an API
@fleet.command()
async def remove(self, ctx, setting=None):
questionOne[ctx.message, ctx.message.id]
count += 1
if questionOne[0] in fleet[str(ctx.guild.id)]:
with open('./databases/destfleet/fleet.json', 'r') as f:
fleeet = json.load(f)
del fleeet[str(ctx.guild.id)][questionOne[0]]
with open('./databases/destfleet/fleet.json', 'w') as f:
json.dump(fleet, f, indent=4)```
Keep getting this error:
del fleeet[str(ctx.guild.id)][questionOne[0]]
TypeError: list indices must be integers or slices, not str```
you cant index a list with a str it must be an int
but its a string in the json
seems like fleet is a list and not a dict
so what do I do?
I tried .remove but it wont work
No errors but doesnt delete anything
you make it a dict ig
Hello everyone, can someone help me with the bot? The problem is that it just doesn't send the message.
from discord.ext import commands
from config import settings
client = commands.Bot (command_prefix = '.')
bot = commands.Bot(command_prefix = settings['prefix'])
async def hello(ctx):
await ctx.send ('1')
async def send_a( ctx ):
await ctx.author.send ('1')
bot.run(settings['token'])```
so dict1 = fleeet[str(ctx.guild.id)][questionOne[0]]
and then del dict1
in the config file, do you have the token like token="102301239123123"
nah it wouldnt change it to a dict
and you also need above the asyncs @client.command()
hm so what do I do 
convert it to a dict with the built in converter
uh you see what da hell is the built in converter
dict()
so like py @client.command() async def hello(ctx): await ctx.send('1')
oops i forgot to add dict(), so dict1 = dict(fleeet[str(ctx.guild.id)][questionOne[0]])
dict1 = dict(fleeet[str(ctx.guild.id)][questionOne[0]])
TypeError: list indices must be integers or slices, not str```
did not help
ok ```py
import discord
from discord.ext import commands
from config import settings
client = commands.Bot (command_prefix = '.')
bot = commands.Bot(command_prefix = settings['prefix'])
@client.command()
async def hello(ctx):
await ctx.send ('1')
@client.command()
async def send_a( ctx ):
await ctx.author.send ('1')
@client.event
async def on_ready():
print("ready")
bot.run(settings['token'])
#in config.py there better be a token```
Does it print ready when you run it
do not quite understand
ok first of all did you run the file?
ohh, ok, i know, little stuppid, sorry
Nonono, its just a general question
Do you know how to ?
sure
its kinda a yes or no question not really a sure answer
sorry i'm just not very good at english because i'm from another country
what then is the answer?
Oh its cool its cool
Ok so lets say you ran it, right, did it print ready?
you need to only convert fleet
oh so flee = dict(fleeet)
that is so
and then I can do flee[str(ctx.guild.id)][questionOne[0]]
are you on a windows computer? (pc) or a mac
kk imma try
pc, windows
you guys do know pc means personal computer right? no matter what os?
File "/Users/vinesh/Documents/GitHub/FlySys22/extensions/fleet.py", line 112, in remove
del dict1[str(ctx.guild.id)][questionOne[0]]
TypeError: list indices must be integers or slices, not str```
and if I write code through VS Code, can it somehow affect?
what is dict1
Wait really? In my school they refer to it as PC
no a full tower is a desktop
No, ok there should be a play button
click it , i figured you were using sublime and you would have to manually run it
I always run like this
with the Play button?
yes
try this:
Are you sure questionOne[0] is an integer and not a string?
import discord
from discord.ext import commands
from config import token
client = commands.Bot (command_prefix = '.')
client = commands.Bot(command_prefix = settings['prefix'])
@client.command()
async def hello(ctx):
await ctx.send ('1')
@client.command()
async def send_a( ctx ):
await ctx.author.send ('1')
@client.event
async def on_ready():
print("ready")
client.run(token)``` and in `config.py` (if there is none create it) and put
```py
token = "token here"```
im having a stroke right now so im just gonna leave😭
Yep, it is a string
same here 
I have a config and a token is registered there
Well, seeing this here, that is definitely not possible to do.
Lists can only be indexed via integer or slice.
questionone is probably a list which youre indexing which it probably returns a str which youre trying to use to index that dict thats the problem sorry i had a brain fart

The error is very clear: questionOne[0] is a string.


So, I guess, let's start back at the very beginning:
What does this intend to do?
gotta take a break
why are you using client and bot???
and naming a bot instance client
basically that was a snippet of the code, and in other words its a json file with planes in there
right
I have the add command working which appends more planes to the json
For now, we shall remain on the single track that we started on, and work on the small problems before attempting to address any big design concerns.
and now I want to remove certain planes (which is what they specify) from the json
alright then
Ok.
How is your JSON built?
and heres my code: (imma send in dms cuz I dont want ppl stealing it)
Describe to me what b777 and b666 do.
it just holds names of planes
Ok, so we add a couple of planes.
We want to remove them now?
Yep
and youre doing that on the list or the whole dict
show code
My first question shall be of design:
Why do you wish to attempt to gameify the removal of these planes?
it was literally fleeet[str(ctx.guild.id)][questionOne[0]]
Well basically its a flight hoster system thing where you can queue pilots, gc, what ever it entails, add staff, add planes, create flights, it posts it when its ready, a whole buncha stuff
what does questionOne[0] return?
a str of B777
^
List.remove("Item name")
what code are you using to remove?
prolly
no fleet.remove(str(ctdsifjiasdjfajdf)...balhaojkasdjfjas)
what.
what is fleet? the dict or the list inside
i can relate
if questionOne[0] in fleet[str(ctx.guild.id)]:
with open('./databases/destfleet/fleet.json', 'r') as f:
fleeet = json.load(f)
# remove this, as it's unnecessary. dict1 = dict(fleeet)
fleeet.remove([questionOne[0])```
the json that is loaded

If you are referencing the value of an item, you may remove that item by calling the list object's remove method.
then youre trying to remove the whole list bro
idkk
dude, get the item (the list you want) from the dict
Okok
AND THEN do .remove
but you dont wanna delete the whole list do you? just things INSIDE the list
wait fleeet.remove([questionOne[0]]) or fleeet.remove(questionOne[0])
Keep in mind that you will still have to reference the guild of which you want to remove the specific plane from.
thats already made 
Yep, so would it be fleet[str(ctx.guild.id)].remove(..)
Try out both and see where they take you.
Ok :)
chill man
isnt fleeet their dict? dicts dont have .remove
We corrected that already.
oh? where
@upbeat gust
Can I not run bot actions through regular functions? Do they have to have a thing like @client.event or @client.command above them?
what bot functions are you thinking of?
Like editing the permissions of a channel
they can be done anywhere if you have the objects needed
Okay then I'm having a different problem I dont understand at all
so like u can make a function wherever
Basically whats happening is I'm starting a thread of a loop that runs forever checking what day it is and also starting the bot in a name == main
And in that loop it checks what day it is, like i said already, and if its sunday the bot will close a channel, and on mondays itll open
you should use a task
yeah ive tried already and I was getting a headache from it; I couldnt understand it at all
multiprocess is literally 1 line to get it to work
IT WORKS TYSM
You're welcome.
then u call the start function on it somewhere
well is that not what this does
Process(target=time_check).start()
whats the problem

Ill post it hold on
The only thing I can hope is that you understand how list indexing works a little better.
import discord
import time
from multiprocessing import Process
import asyncio
botToken = 'not your token'
submissionChannelID = 938266082899267607
winnerChannelID = 940746269121474600
winnerRoleID = 940746379205181480
currentDay = ""
client = discord.Client()
#client.get_channel(938266082899267607)
async def set_channel(value):
overwrites = {client.get_channel(submissionChannelID).guild.default_role: discord.PermissionOverwrite(send_messages=False)}
await client.get_channel(submissionChannelID).edit(overwrites=overwrites)
def time_check():
global currentDay
while True:
time.sleep(1)
currentTime = time.ctime()
if "Sun" in currentTime:
if currentDay != "Sunday":
set_channel(False)
currentDay = "Sunday"
#find the winner and give them the winner role, and remove the winner role from the previous winner
channelID = client.get_channel(938266082899267607)
channelID.send("test message")
print("its sunday!!")
elif "Mon" in currentTime:
if currentDay != "Monday":
set_channel(True)
currentDay = "Monday"
print("its monday!!")
elif currentDay != "N/A":
set_channel(False)
currentDay = "N/A"
print("not monday or sunday")
@client.event
async def on_ready():
print('We have logged in as {0.user}'.format(client))
@client.event
async def on_message(message):
if not message.attachments and message.channel.id == submissionChannelID:
await message.delete()
else:
await message.add_reaction("❤️")
if __name__ == "__main__":
Process(target=time_check).start()
client.run(botToken)```
howdy
Okay so, in order to call the set_channel it has to be awaited, but then to call the time_check which is where the set_channel is called it also has to be awaited which then brings me down to the process which I literally cant await
which is why we want a task
tasks are async
Oh okay
Yep I do
multiprocessing is restricted to sync?
thats nice
im not sure how you can start async functions sorry
I have no idea either but I think ill just do the tasks 🙂
you can set a time kwarg for it to run every day at that time
youll need 2.0 for that tho
okay, Ill just run it every few minutes or something, thank you very very much
how do I catch a asyncio.TimeoutError
import asyncio
try:
raise asyncio.TimeoutError
except asyncio.TimeoutError:
...
kk tysm
how do i get a percentage of a number? for example i do NOT want to get 3/5 for 60%
i want to take a input number(say 100) and then take like 3% off it
and get whats left and what is taken
Like a discount?
20% discount off $100 would be $80, is that what you mean?
Ah. It's (1 - percent/100)*number
ok thanks
For example, 20% of 100 is (1 - 20/100)*100 = (0.8)*100 = 80
ya i see
And it works for numbers other than 100 as well, by the way
i know
That's against the TOS, so no
ok, can someone tell me how to send messages through the bot to everyone who is on the server?
this my code
from discord.ext import commands
from config import settings
bot = commands.Bot(command_prefix = settings['prefix'])
@bot.command()
async def hello(ctx):
await ctx.send ('1')
@bot.command()
async def send_a( ctx ):
await ctx.author.send ('Пососи')
@bot.command()
async def all(ctx):
@bot.event
async def on_ready():
print("ready")
bot.run(settings['token'])
!rule 5
5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.
ummm am i doing something wrong? what is wrong here if I want my bot to send messages to people who are on my server?
selfbots are against TOS.
and sending messages to all people in the server is questionable. it is also very error prone in case some users have dms closed
is it bad practice to take an instance of a class as an argument for another class?
so I'm not talking about him, but an default bot
Why not subclass it?
well, a lot of things do that
technically every object comes from a class
already subclassing another one
that's pretty much inheritance, no?
ehh depends on the usage
Well why not a third time?
it could be described as composition
all my friends have it open
never heard of this OOP concept before tbh
unless I forgot
why not ping everyone in the server then
i was having trouble doing it, found that just taking the instance as pos arg is easier
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
we are 8 people on the server including the bot and everyone has DM open
https://paste.pythondiscord.com/ipiserexux
this is the code in question
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
again why not just send 1 message that pings everyone, rather than sending out 8 messages and potentially tripping discord's anti spam
multiple inheritance
ya but when i use self in bMultiDerived, it dervies from Base1 and when it doesn't find the func/attr it raises error
https://en.wikipedia.org/wiki/Composition_over_inheritance
the idea is storing other instances as attributes rather than inheriting their methods
maybe because i want to? and my friends don't mind, they themselves tried to help me do it in c#, but it's very difficult there
Then just use the super()
!d super
class super([type[, object-or-type]])```
Return a proxy object that delegates method calls to a parent or sibling class of *type*. This is useful for accessing inherited methods that have been overridden in a class.
The *object-or-type* determines the [method resolution order](https://docs.python.org/3/glossary.html#term-method-resolution-order) to be searched. The search starts from the class right after the *type*.
For example, if [`__mro__`](https://docs.python.org/3/library/stdtypes.html#class.__mro__ "class.__mro__") of *object-or-type* is `D -> B -> C -> A -> object` and the value of *type* is `B`, then [`super()`](https://docs.python.org/3/library/functions.html#super "super") searches `C -> A -> object`.
The [`__mro__`](https://docs.python.org/3/library/stdtypes.html#class.__mro__ "class.__mro__") attribute of the *object-or-type* lists the method resolution search order used by both [`getattr()`](https://docs.python.org/3/library/functions.html#getattr "getattr") and [`super()`](https://docs.python.org/3/library/functions.html#super "super"). The attribute is dynamic and can change whenever the inheritance hierarchy is updated.
oh yea, i couldve used super there
well, afaik you may risk bot termination regardless of who your bot sends it to
can super be used to access class attrs?
open the same DM, you don’t understand what I’m telling you, I’ll throw you a screen
c# is doable, regardless of that fact. Anyhow it is inappropriate, we won't help create any kind of loop that sends multiple messages.
why ?
e.g. a Person storing a Wallet instance vs a Person that inherits Wallet
Because we don't know you? We've had multiple people asking for this previously and after asking @novel apex they said that it's too inappropriate. If you want us to help ask @novel apex if you can and have a mod come over to approve it.
It's against the TOS. period. your use case doesn't matter
How do you imagine that I will use it for selfish purposes, if you do not have the administrator role, then you do not invite the bot, so even if I would like to harm someone, then I must have the administrator role
I have already started but I don't know how to use it
async def guild_message(ctx):
for Every_Member in ctx.guild.members:
if Every_Member.bot != True:
await Every_Member.send('Ваше сообщение тут')```
I'm not going to further discuss this, and I hope people here won't as well. Please confront @novel apex in DM.
class A:
pass
class B:
...
self.a = 0
class Double(A, B):
...
how do i get access to self.a in Double
it's a long time
@tasks.loop()
@client.event
async def changeprs():
await client.change_presence(status=discord.Status.online,
activity=discord.Game(f'{numofdays(date1, date2)} Tage'))
await asyncio.sleep(3)
await client.change_presence(status=discord.Status.online,
activity=discord.Game("04.07.21"))
how can i loop this
i believe changing presence every 3 seconds would be ratelimited, so something more like 2-10 min would be better
also i dont think you want the event decorator
what should i do know to loop it
!e ```py
class A:
pass
class B:
def init(self) -> None:
self.a = 0
class Double(A, B):
def init(self) -> None:
super().init()
print(self.a)
Double()
@cloud dawn :white_check_mark: Your eval job has completed with return code 0.
0
Okay so if we have a second inheritance we're also going to need to execute the init.
That in this case takes no args or kwargs.
personally i would store a list of activity text, cycle through them in the loop and format the text before changing the presence
im pretty new to python can you explain me how
well a simple implementation of cycling can be done by storing the index of the next presence to change to
activity_texts = ['{remaining_days} left', '{end_date}']
i_activity = 0
@tasks.loop(minutes=10)
async def cycle_activities():
text = activity_texts[i_activity]
text = text.format(
remaining_days=...,
end_date=...
)
await bot.change_presence(activity=discord.Game(text))
# add one to the index and have the modolo cycle to the start
i_activity = (i_activity + 1) % len(activity_texts)```
if message.content.startswith("start"):
role = message.guild.get_role(943243423446605834)
for i in role.members:
user = i.id
LogCMD("buyers.json", {"UserID": user})
print(user)
y isnt this working
its not outputting anything
@fresh sable has asked how to make a bot command that DMs a certain group of people. We will allow it as long as the list of people to be DMed is hard-coded (and thus can't trivially be adapted to mass-DM).
so would for-looping over a list of ids be acceptable?
if the list is short enough that it does not constitute API abuse, that is fine.
if message.content.startswith("start"):
role = message.guild.get_role(943243423446605834)
for i in role.members:
user = i.id
LogCMD("buyers.json", {"UserID": user})
print(user)
y isnt this working
its not outputting anything
Okay thanks stelercus.
what is the i_activity
your event might not have fired either due to missing intents, permissions, or being overridden by another event handler
as i said im pretty new to python
its just storing the current index in the list of activities
x = ['a', 'b', 'c'] doing x[0] gives 'a', doing x[2] gives 'c', etc.
would an example of a loop be
@tasks.loop(minutes=1)
async def check_flight():
time = datetime.datetime.now()
print(time)
check_flight.start()
does anyone know how to get a role ID by its name
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/master/api.html#discord.utils.find "discord.utils.find").
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable "(in Python v3.10)")s...
you could use this
@hushed galleon @sick birch @cloud dawn @fresh sable
after looking into it further we've decided under rule 5 to not allow help for this, as its potential and likeliness for abuse is moderately to fairly high
uh
!mute 498171366910984193
:incoming_envelope: :ok_hand: applied mute to @fresh sable until <t:1648608086:f> (59 minutes and 59 seconds).
Not because you are Ukrainian just because it isn't allowed.
Cool, thanks for the heads up
!unmute 498171366910984193
:incoming_envelope: :ok_hand: pardoned infraction mute for @fresh sable.
seeing as you've agreed to us via @novel apex to follow our #rules and #code-of-conduct i expect full compliance from this point onward.
Traceback (most recent call last):
File "C:\Users\hackt\OneDrive\Escritorio\coldevsbot\main.py", line 48, in <module>
class Dropdown(discord.ui.Select):
AttributeError: module 'discord' has no attribute 'ui'```
Please help,
maybe you did not install the module that you are missing?
pip install ui no working
PS C:\Users\hackt\OneDrive\Escritorio\coldevsbot> pip install ui
Requirement already satisfied: ui in c:\users\hackt\appdata\local\packages\pythonsoftwarefoundation.python.3.9_qbz5n2kfra8p0\localcache\local-packages\python39\site-packages (0.1.4)
wait now i will help you
please
as I understood when installing python, you did not set Path ?
What
It is saying it's already installed
That's not the issue
Did you install discord.py 2.0?
Are you using 2.0?
can i send youtube video ?
3.0
in this channel
3.0?
2.0*
is it relevant to discord bots?
i can help
no
Then don't post it 🙂
ok i send in dm
don't think any video would help for this specific problem. it's likely they have an old version of dpy or smth
you yourself told me the video isn't related to discord bots, so how could it possibly help them?
Indentation
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
Please don't advertise here.
maybe during installation, like me, he didn’t check the Path box and because of this he can’t install, but with the help of the video that I sent him, he will be able to do it
can u all suggest me a way to store player's progress in the rpg game bot that i built?
like userid+item name
but im facing scoping error with calling userid
@umbral tapir please read our #rules. while your article is about discord bots, sharing that unprompted is self-promotional
That's unrelated to their issue though
Use a database
...
of course i know use a database
but in what way
like "userid + itemname" or wat
wdym
i need to keep their progress items
i think it has
You can make a table with their items and stuff
im using replit
i dont think replit has that function
Then don't use replit
🤦♂️
i mean, isn't there some way with replit?
the progress doesn't necessarily have to permanent like 24/7 right?
Wdym
if this is a bot that isn't on 24/7, then why not just use a cache for game progress?
(i'm assuming this bot isn't persistently on 24/7, but i'm not sure)
Just put it in replit db or something
yeah i've heard of replitdb
replit also allows the useage of sqlite
Would require a keep_alive.py file and a uptimerogot
It does
oh that's cool
replit db is json based, so using sqlite is actuallt better since it best paired with aiosqlite.
Yep
Discord-related data is best modelled using a relational database, so a relational database might be easier to work with unlike replitdb
replit shouldn't be used for hosting either way
For small bots it doesn't really matter.
I suppose not, but it's not necessarily bad to build up a good infrastructure from the start
Yea, speaking of that how do I get the data that is stored on my host like the sql file
Replit database
the thing is, what if you're just learning? if you know the downsides of replit, why can't you use it so long as it fits your needs?
i know the downsides
Sqlite3 best :)
i dont like local file databases
Replit is best for beginner
but if i'm making a personal bot strictly for learning purposes that no one else is gonna use..?
cant be used by mutiple systems and its not as easy to visualize
They're good for small projects, but are hard to scale and insecure
If so there's still really no reason to use replit
Hmm so if I were to use a online sql database then that would be better
7ms to get a row from 5000000 of them
true. would just run it locally lol
Exactly
but just saying "don't use replit" isn't a helpful suggestion
MySQL Hosting for free. Signup now for your free MySQL database hosting and be live in minutes.
Not really, it’s free no downloads required just code and 24/7 uptime
Define "online sql database"
explain why and give alternatives
thats a option to use that website
Yes exactly what I’m talking about
24/7 uptime, not quite
Unless you're using some hacky method like keep alive
In JavaScript you can you phpmyadmin with sql
Or uptime robot or whatever
shhhh
u have to renew it every week and it has a storage limit but u can also use google cloud and they are pretty cheap

Google cloud, aws, microsoft azure are all professional hosting services that scale very well, so start off small, pay for what you need and go from there
There are a lot of downsides
Heroku isn't much better either
Heroku also has issues
I mean comparing sqlite to mysql nowadays in async i think sqlite is pretty close to beating it. Since the async pypi for mysql is just that bad.
I know I’m just finding temporary places untill I can pay for a host and a proper db
What about docker?
Docker is not a hosting platform
If you got a vps you can just local host the db on the vps.
As a database
It's a containerization tool. It can be used in aws eks for instance
Docker is not a database either
It's a mini virtual machine
Really? I was told it was a database
That's misinformation
Oh wow , what things can you run on there
Anything
Hm ok
You could use it as a db tough. don't recommend
Hm
It's used a lot in professional environments where you want to run someone else's applications but don't want to install the language, dependencies, and generally bloat your computer
All you need is docker, it sets up a mini virtual machine, installs the language, a program dependencies, and runs it within that container, completely isolated from your host computer
Ah so it’s chat a place to house information for running
Basically docker is a local vps.
No, it's a mini computer within your computer
Nice
It can run any program in a isolated environment
But I can’t run a bot or a website on it
Sure you can


i see

