#discord-bots

1 messages · Page 940 of 1

cold sonnet
#

dude probably copied the post's link not the image's one

slate swan
#

that's what i'm saying

#

but okimii seems to disagree

#

imgur uses a subdomain to serve the images

#

it should still display bruh

cold sonnet
#

no

slate swan
#

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

slate swan
tough lance
#

Use PIL

#

In an executor tho

slate swan
#

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

cold sonnet
#

what if you want the sentence to be returned capitalized

maiden fable
#

😔 the nickname

slate swan
#

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!"?

paper sluice
#

can sm1 send dpy's discord? cant seem to find it

cold sonnet
#

well you can't just do that maybe the dude's typing 300wpm

tough lance
paper sluice
#

ty

slate swan
#

how would you even calculate the typing speed?

maiden fable
#

!d discord.on_typing

unkempt canyonBOT
#

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.
astral coral
#

i am new

slate swan
#

as in WPM

tough lance
slate swan
#

because people don't type at a constant rate throughout a message

astral coral
maiden fable
#

Well that is the only way

astral coral
#

i am beginner

slate swan
#

yep

tough lance
#

Pil might be a good way

maiden fable
#

U mean making a typeracer command? @tough lance

slate swan
#

PIL if you want to create an image on the fly

tough lance
#

I'm not the one making the command

slate swan
#

just be careful on implementing it

tidal hawk
tough lance
#

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

maiden fable
#

Or use an API

astral coral
#

how to start?

slate swan
#

how to start what

tough lance
#

Discord bot coding

slate swan
#

..

slate swan
cold sonnet
#

no it's drawing

slate swan
tough lance
#

Where did the prev one go

unkempt canyonBOT
#

@slate swan :white_check_mark: Your eval job has completed with return code 0.

Drawing.....
slate swan
hoary cargo
spring flax
#

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)

hoary cargo
#

And error

spring flax
#
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```
slate swan
spring flax
#

but what have i not awaited

slate swan
#

Ctx is not defined ?

slate swan
spring flax
#

i haven't even used ctx

slate swan
#

68

#

Line 68

dense swallow
#

what's line 68? can u send the code

slate swan
#

Many errors

spice adder
#

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

dense swallow
#

get_guild*

slate swan
#

Lol

dense swallow
#

bruh

slate swan
#

Another one

fluid spindle
#

Is there any way to disable the logging done by disnake in the terminal?

spring flax
# dense swallow what's line 68? can u send the code

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

unkempt canyonBOT
#

get_guild(id, /)```
Returns a guild with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
dense swallow
#

finally

slate swan
#

U get from google!

dense swallow
spring flax
#

sigh

#

like i said, i know that. But I can't find what

spice adder
#
  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
slate swan
#

Nvmd

dense swallow
#

just pass in the id @spice adder

slate swan
#
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..
slate swan
#

Seriously

spice adder
#

I see

#

Misread the snippet

dense swallow
#

and what is flags

spring flax
toxic thicket
#

I don’t know how to make the warns not global, but different on each server, help me.
Sql

slate swan
#

then whenever you query it, you could fetch allthe results and iterate through them

#

only if there is a better way

dense swallow
#

insert the warns.. then fetch it using select * from table_name

south jetty
#
        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)```
dense swallow
#

insert into table_name with values..

proven birch
#

@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)```
dense swallow
#

then use the select query

slate swan
dense swallow
#

yeah

dense swallow
proven birch
south jetty
toxic thicket
dense swallow
#
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​)
slate swan
# toxic thicket can i have an example please?
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```
toxic thicket
#

Hm

austere vale
#
@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?

hybrid mural
#

ctx.voice_bot?

#

perhaps voice_state?

#

no wait

slate swan
#

!d discord.Guild.voice_client

unkempt canyonBOT
#

property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/master/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
hybrid mural
#

^

hybrid mural
#

Ashley the mvp frfr

slate swan
#

!d discord.ext.commands.Context.voice_client

unkempt canyonBOT
#

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.
slate swan
hybrid mural
#

no help them tf

slate swan
#

you will

hybrid mural
#

wdym

#

i aint a pro

slate swan
#

learn from your mistakes

hybrid mural
#

nah you know your commands

#

i cant learn from my mistakes by not knowing the commands that are there

slate swan
hybrid mural
#

offensive?

slate swan
hybrid mural
#

if my hunch is correct jokes are not to be meant offensive or defensive or anything

#

jokes are jokes

slate swan
#

well, this is python server

hybrid mural
#

youre right

slate swan
#

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:
balmy ivy
#

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

slate swan
slate swan
balmy ivy
#

i dont need id i need mention

maiden fable
#

You cannot mention anything in the field title 😔

slate swan
#

I just wrote that and got ignored

maiden fable
#

(That is what she said but u ignored her sooo 🤷)

balmy ivy
maiden fable
#

you can do @{member.name} but u won't get the blue mention box around it

slate swan
#

@member.name

#

cursed

balmy ivy
maiden fable
#

Its been ages since I have coded, don't

maiden fable
slate swan
alpine furnace
slate swan
gaunt ice
#

whats the issue

alpine furnace
#

Nevermind, it’s been said already

gaunt ice
#

ok

slate swan
#

xenoren will change discord

alpine furnace
#

Could just do str(message.author) 🤷‍♂️

gaunt ice
slate swan
alpine furnace
#

Sure

maiden fable
alpine furnace
#

Yes

#

It still has the effect of identifying the user

balmy ivy
#

embed2.add_field(name="**Coach:**", value=f"{message.author.mention} ``{message.author}``")

#

this what i had last time

slate swan
#

fails to understand

alpine furnace
#

They don’t want a line break

slate swan
#

I'll just leave

maiden fable
#

Well its gonna be difficult

balmy ivy
#

how so

maiden fable
#

values cannot be multiline 🤷

slate swan
balmy ivy
#

i am just trying to firgure it out

maiden fable
slate swan
gaunt ice
#

this works but i want someother api

#

any other channels for api ideas

gaunt ice
#

okkk

maiden fable
south jetty
#
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```
spice adder
#
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'

maiden fable
#

remove the g

south jetty
# south jetty ```py line 397, in request raise HTTPException(response, data) disnake.error...
        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:")
            ]
            )
        ]
        )```
maiden fable
#

the :Roblox: emoji

gaunt ice
#

oof

maiden fable
#

wrong name

south jetty
#

i see it as ":Roblox:"

#

uh

#

or this wont work?

slate swan
#

but if your bot has any mutual guild tht has that emoji

maiden fable
#

that will work @south jetty

slate swan
#

and has the permission to use external emoji

#

then bot should be able to use it

south jetty
maiden fable
slate swan
south jetty
#

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 = "🤖 ")
            ]
            )
        ]```
slate swan
#

wait.. it's saaying invalid emoji for the universal emojis too?

south jetty
#

yes

slate swan
#

bruhh

#

i mean.. i've no idea then

south jetty
#

ok fixed it

#
Command raised an exception: AttributeError: module 'disnake_components.client' has no attribute 'wait_for'
maiden fable
#

Show code

#

Ah wait

#

U need to use disnake.Client

#

Not disnake_components.client

south jetty
#
        interaction = await client.wait_for("select_option", check=lambda i: i.component[0].value=="TTC")
        await interaction.respond(content=f"{e1}")```
south jetty
hasty bison
#

any1 can help me make my bot send private messages to a user

slate swan
#

!d discord.Member.send ?

unkempt canyonBOT
#
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**.
runic siren
#

!e
while True:
print("test")

hasty bison
#
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?

slate swan
toxic thicket
#

could you add me as a friend? @slate swan

modern fiber
#

how do I get a bot dm a new people who join a server?

#

like on.join_member or ?

slate swan
#

you use a listener to execute code whenever the specific event is triggered

slate swan
#

!d discord.ext.commands.Bot.listen

unkempt canyonBOT
#

@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...
slate swan
unkempt canyonBOT
#

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.
craggy cloak
#

I tried to install slash commands but when I try to run a cmd it isn't working?

crimson compass
slate swan
slate swan
slate swan
craggy cloak
#

no traceback I just installed pip install -U discord-py-slash-command

modern fiber
#

Guys how do I get bot DM the new joined people?

sick birch
#

And pair that with member.send

modern fiber
#

so it will be await member.send?

#

brb lemme try doing it

slim ibex
#

use a database

modern fiber
#
@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.

neon plover
#

My discord bot requires Python v4 but I can't find a docker for it, anyone has one?

slate swan
#

thats crazy im still on 3.10rooPopcorn

neon plover
#

oh it hasnt released

slim ibex
neon plover
#

ERROR: Could not find a version that satisfies the requirement discord_slash (from versions: none)
ERROR: No matching distribution found for discord_slash

slim ibex
#

You can use a database to circumvent that

slate swan
neon plover
#

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

slate swan
#

why even download the lib

slim ibex
#

^

slate swan
#

just use main

foggy scroll
#

What is this IDE ?

#

is this mac ?

slate swan
foggy scroll
#

oh sry

supple crescent
#

@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?

slate swan
#

show full tb

slate swan
spring cape
#

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.

unkempt canyonBOT
#

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.
spring cape
#

but thanks nonetheless!

modern fiber
#

@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?

supple crescent
# slate swan show full tb

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'

slate swan
#

demm

modern fiber
#

Anybody lol

slate swan
spring cape
#

Aaah ok

tidal hawk
slate swan
spring cape
#

Thank you very much :) @slate swan

azure tulip
#

How to fix it?

south jetty
#
        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
neon plover
#

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

slate swan
neon plover
#

Hm?

#

What do I give it?

slate swan
neon plover
#

It has admin role

slate swan
#

it doesnt matter

#

it needs perms in dev portal

azure tulip
slate swan
neon plover
supple crescent
#

channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites)

slate swan
#

!d discord.TextChannel.send

unkempt canyonBOT
#
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**.
slate swan
azure tulip
neon plover
#

How do I give bot permission in dev portal

south jetty
slate swan
slate swan
#

@slate swan would you mind taking over for me in trying to learn flaskcatsip

supple crescent
neon plover
#

No idea, I’m getting missing Access and okimii said I need to add permission in portal

slate swan
neon plover
#

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

azure tulip
flat solstice
#

Is there a bot command/tga here on why not to host on replit

slate swan
azure tulip
slate swan
#

i knowpeeposhy

south jetty
#
        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
neon plover
#

I don’t think it’s a code problem

#

It’s slash commands

neon plover
#

I’ve had error over error because of me trying to add Slash Commands

ripe harness
#

Hi, anyone knows why @bot.on_ready would take like 3 minutes to execute

slate swan
#

nicely done binds

south jetty
slate swan
slim ibex
slim ibex
slate swan
#

!d break

unkempt canyonBOT
#

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...
slate swan
ripe harness
slim ibex
#

go lang = bad

neon plover
#

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

azure tulip
neon plover
#

I don’t think so, how do I do that

ripe harness
slate swan
slate swan
flat solstice
slate swan
unkempt canyonBOT
#

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.
slate swan
#

on_ready gets triggered on cache population

#

thinkmon i see

ripe harness
slate swan
neon plover
#

Alright

ripe harness
slate swan
#

alr

ripe harness
#

i will try on_connect (to get what i need) maybe it'll load faster x)

slate swan
ripe harness
#

i m playing with selfbots i know it s against tos but i m lazy and some simple comamnds won t hurt anyone

slate swan
#

still against tos and we dont talk about self bots here

ripe harness
#

roger that

left crater
#

whats a self bot?

ripe harness
#

wont mention em again

slate swan
left crater
#

oh

ripe harness
#

I have other bots but but yeah dn why i wanted one of thsoe

neon plover
#

I gave it application.command

kindred drum
#

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?

sick birch
#

Maybe you meant members, plural

south jetty
#
        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

sick birch
#

If you only want it to respond to one option why include others

south jetty
kindred drum
#
@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

slim ibex
#

you just need to use ctx.guild.members

slate swan
#

Im confused why i am getting this error

slim ibex
#

The shell exited because something occurred that was unexpected

#

status 127 means the command wasn’t found

supple crescent
#
@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

slim ibex
#

The error is in that line?

supple crescent
#

yup

#

idk it worked b4, hjavent touched it

#

do u want the whole hastebin ?

slim ibex
#

I don’t really have time to help with this rn tbh. Hopefully someone else comes around soon 🗿

tidal hawk
supple crescent
#

!paste

unkempt canyonBOT
#

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.

tidal hawk
#

What does print(ctx.guild) return?

supple crescent
#

just make it run that?

tidal hawk
#

@bot.command(name="start")
async def start(ctx):
guild = ctx.guild
print(guild)

supple crescent
#

lemme check

#

@tidal hawk it saus the name of the server

tidal hawk
supple crescent
tidal hawk
#

Bruh what is 'id':target.id

#

Try it without overwrites, and send the log

supple crescent
#

how would i do that, soory?

tidal hawk
#

commendt out the overwrites {}

supple crescent
#

ahhh

tidal hawk
#

and remove the overwrite kwarg from text_channel

#

Let's see if it creates the text channel without it

supple crescent
#

now the overwites in channel1 = await guild.create_text_channel(f"private-channel{ctx.author}", overwrites=overwrites) is undefined

tidal hawk
#

remove the overwrites=overwrites

hushed galleon
#

one of the keys in your overwrite dict is probably None

tidal hawk
#

Mhm

supple crescent
#

it works @tidal hawk

tidal hawk
#

yeah the problem was in overwrites

south jetty
tidal hawk
supple crescent
#

yeah

#

thas a big prob

hushed galleon
#

could be that your id didnt match any role

supple crescent
#

NOOOOOOO

#

FUCKKKKK THATS WHAT IT IS

tidal hawk
#

Lmao - laughing my ass off

supple crescent
#

BRUHH

tidal hawk
#

Happens to best of us

hollow quarry
#

hey, please avoid using ableist language here

supple crescent
#

shit sorry

tidal hawk
#

xD

hollow quarry
#

no worries

tidal hawk
#

ableism.. new word added to my dictionary

sage otter
#

I didn’t know what that meant either until that same mod warned me for the same reason as that guy just now

tidal hawk
#

Something new everyday

alpine pewter
#

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.

tidal hawk
#

try except should work

#

100%

alpine pewter
#

Right, I just did it wrong lol

tidal hawk
#

Send the snippet how you did it

slate swan
alpine pewter
#
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

slate swan
#

you could just use dict.get() to get a value and if it doesnt exist it just returns None

tidal hawk
#
@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')
alpine pewter
unkempt canyonBOT
#

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").
slate swan
#

does anyone know node.js?

tidal hawk
#

Who is node js

alpine pewter
tidal hawk
#

and yeah.. check out the dict.get, it's more cleaner way

alpine pewter
#

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 (:

slate swan
#

not really

slim ibex
slate swan
#

its just async lmao

alpine pewter
#

Oh, it took it 20s before, then it only took like .5s after
I just assumed it's faster

#

Might be my bad code

supple crescent
#

is there anywhere i could ask for somebody to try and break my bot? i want to stress test it for any exploits

south jetty
#

useless server

alpine pewter
supple crescent
#

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} ")
slim ibex
tidal hawk
tidal hawk
supple crescent
#

but ik

tidal hawk
#

Yes you can 🗿

supple crescent
#

ok that seems easy enough, can i add a msg to say like : oops rthis is on cooldown

tidal hawk
#

yep

slate swan
#

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"))
quaint forum
#

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?

oblique laurel
#

Rip, PascalCase

oblique laurel
quaint forum
#

whats wrong with pascal and what do you mean outside?

oblique laurel
#

Pascal is only used for class names

quaint forum
#

If I dont include await the bot wont edit the channel

#

what case should I use then for functions?

oblique laurel
oblique laurel
#

Thats why you see on_message instead of OnMessage

quaint forum
#

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
slate swan
#

is there a way to check the date in audit logs?

oblique laurel
slate swan
oblique laurel
#

Theres a tab on the left that lists everything in the bot pretty much

slate swan
#

its created_at

oblique laurel
#

👍

slate swan
supple crescent
#

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()
sick birch
#

Why is your cooldown decorator inside a function

#

It's supposed to decorate a function

slate swan
slate swan
supple crescent
#

🤦‍♂️

flat solstice
#

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()}``")

final iron
#

// is a comment iirc

pallid meadow
#

there is no closing bracket }

#

actually

#

I think I am wrong nvm

final iron
#
ddddd
// aaaa
#

yup

#

It's like javascript

slate swan
#

yeah iirc comments in js are //

flat solstice
#

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

final iron
slate swan
#

yeah

final iron
#
let a = "a"
// my comment
#

idk if that's valid

#

I don't know javascript

pallid meadow
#

ye

#

that's correct

flat solstice
# final iron json syntax highlighting

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

pallid meadow
#

if you are making an mutable variable

slim ibex
#

variables declared with let are mutable

final iron
#

There's also var right

#

Or am I thinking of something else

slim ibex
#

that is old

#

that does exist in JS though

#

let and var have different scopes

sick birch
#

var is usually not recommended

#

but if you're running something like babel or tsc it'll use var to support older browsers

slim ibex
#

^

slate swan
#

how can i change the UTC time to secs

#

im not talking abt unix codes

sick birch
flat solstice
sick birch
#

yeah that could help

cloud dawn
sick birch
#

they want to use a raw dict to construct an embed

cloud dawn
#

Doesn't to_dict give an example

cloud dawn
#

That is what I was referring to when I gave you the method.

sick birch
#

I don't really get why you'd want to use a raw dict though

flat solstice
#

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

cloud dawn
sick birch
#

for embeds?

flat solstice
sick birch
#

I see

#

But I don't really see how an embed builder helps you make a modal?

flat solstice
#

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)

flat solstice
sick birch
#

Oh I see

#

Though you can still use the native methods for that

flat solstice
#

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

sick birch
#

Well yeah like an API

silent ermine
#
    @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```
slate swan
#

you cant index a list with a str it must be an int

silent ermine
slate swan
silent ermine
#

I tried .remove but it wont work

#

No errors but doesnt delete anything

slate swan
#

you make it a dict ig

fresh sable
#

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'])```
silent ermine
#

and then del dict1

silent ermine
slate swan
silent ermine
silent ermine
slate swan
#

convert it to a dict with the built in converter

silent ermine
slate swan
#

dict()

fresh sable
#

ohhh

#

no

silent ermine
#

so like py @client.command() async def hello(ctx): await ctx.send('1')

silent ermine
# slate swan dict()

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```
silent ermine
# fresh sable 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

fresh sable
#

do not quite understand

silent ermine
fresh sable
#

ohh, ok, i know, little stuppid, sorry

silent ermine
#

Do you know how to ?

fresh sable
silent ermine
fresh sable
fresh sable
silent ermine
silent ermine
silent ermine
slate swan
silent ermine
silent ermine
silent ermine
fresh sable
slate swan
#

you guys do know pc means personal computer right? no matter what os?

silent ermine
# slate swan yep
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```
fresh sable
silent ermine
silent ermine
slate swan
silent ermine
#

click it , i figured you were using sublime and you would have to manually run it

fresh sable
silent ermine
fresh sable
silent ermine
#

try this:

odd prawn
silent ermine
# fresh sable yes
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"```
slate swan
#

im having a stroke right now so im just gonna leave😭

silent ermine
silent ermine
fresh sable
odd prawn
slate swan
odd prawn
#

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

slate swan
#

yeah

#

thanks to refisio i didnt had another brain fartrooNap

slate swan
silent ermine
odd prawn
#

So, I guess, let's start back at the very beginning:
What does this intend to do?

slate swan
upbeat gust
odd prawn
#

You really don't need to worry about that.

#

Not now, anyways.

upbeat gust
silent ermine
#

I have the add command working which appends more planes to the json

odd prawn
silent ermine
#

and now I want to remove certain planes (which is what they specify) from the json

silent ermine
#

ive tried .remove but that did nothing

#

no errors of any sort

odd prawn
#

Ok.
How is your JSON built?

silent ermine
#

and heres my code: (imma send in dms cuz I dont want ppl stealing it)

odd prawn
#

Describe to me what b777 and b666 do.

silent ermine
odd prawn
#

Ok, so we add a couple of planes.
We want to remove them now?

upbeat gust
upbeat gust
odd prawn
#

My first question shall be of design:
Why do you wish to attempt to gameify the removal of these planes?

silent ermine
silent ermine
upbeat gust
silent ermine
upbeat gust
#

what code are you using to remove?

silent ermine
silent ermine
upbeat gust
#

what is fleet? the dict or the list inside

slate swan
odd prawn
#
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])```
silent ermine
slate swan
odd prawn
#

If you are referencing the value of an item, you may remove that item by calling the list object's remove method.

upbeat gust
silent ermine
upbeat gust
#

I dont think you can even do taht

#

.remove on a dict

upbeat gust
upbeat gust
#

AND THEN do .remove

upbeat gust
silent ermine
odd prawn
# silent ermine Okok

Keep in mind that you will still have to reference the guild of which you want to remove the specific plane from.

silent ermine
odd prawn
silent ermine
silent ermine
upbeat gust
odd prawn
#

We corrected that already.

upbeat gust
quaint forum
#

Can I not run bot actions through regular functions? Do they have to have a thing like @client.event or @client.command above them?

upbeat gust
quaint forum
#

Like editing the permissions of a channel

upbeat gust
#

they can be done anywhere if you have the objects needed

quaint forum
#

Okay then I'm having a different problem I dont understand at all

upbeat gust
#

so like u can make a function wherever

quaint forum
#

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

quaint forum
#

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

upbeat gust
#

task you just create a function

#

and put args into the decorator

silent ermine
odd prawn
#

You're welcome.

upbeat gust
#

then u call the start function on it somewhere

quaint forum
#

well is that not what this does

Process(target=time_check).start()

silent ermine
quaint forum
#

Ill post it hold on

odd prawn
quaint forum
#
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)```
odd prawn
#

howdy

quaint forum
#

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

upbeat gust
#

tasks are async

quaint forum
#

Oh okay

quaint forum
#

multiprocessing is restricted to sync?

upbeat gust
quaint forum
#

thats nice

upbeat gust
quaint forum
#

I have no idea either but I think ill just do the tasks 🙂

upbeat gust
upbeat gust
quaint forum
#

okay, Ill just run it every few minutes or something, thank you very very much

silent ermine
#

how do I catch a asyncio.TimeoutError

final iron
round robin
#

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

sick birch
#

20% discount off $100 would be $80, is that what you mean?

round robin
#

yes

#

how would i caculate that with a number other then 100

sick birch
#

Ah. It's (1 - percent/100)*number

round robin
#

ok thanks

sick birch
#

For example, 20% of 100 is (1 - 20/100)*100 = (0.8)*100 = 80

round robin
#

ya i see

sick birch
#

And it works for numbers other than 100 as well, by the way

round robin
#

i know

fresh sable
#

it's only for my server

sick birch
#

That's against the TOS, so no

fresh sable
#

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'])
slim ibex
#

!rule 5

unkempt canyonBOT
#

5. Do not provide or request help on projects that may break laws, breach terms of services, or are malicious or inappropriate.

fresh sable
#

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?

slim ibex
#

and sending messages to all people in the server is questionable. it is also very error prone in case some users have dms closed

paper sluice
#

is it bad practice to take an instance of a class as an argument for another class?

fresh sable
hushed galleon
#

technically every object comes from a class

paper sluice
slim ibex
#

that's pretty much inheritance, no?

hushed galleon
#

ehh depends on the usage

cloud dawn
hushed galleon
#

it could be described as composition

fresh sable
slim ibex
#

unless I forgot

hushed galleon
paper sluice
#

!paste

unkempt canyonBOT
#

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.

fresh sable
paper sluice
cloud dawn
hushed galleon
#

again why not just send 1 message that pings everyone, rather than sending out 8 messages and potentially tripping discord's anti spam

slim ibex
#

multiple inheritance

paper sluice
hushed galleon
fresh sable
slim ibex
#

!d super

unkempt canyonBOT
#

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.
paper sluice
#

oh yea, i couldve used super there

hushed galleon
paper sluice
#

can super be used to access class attrs?

fresh sable
cloud dawn
hushed galleon
cloud dawn
# fresh sable why ?

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.

sick birch
fresh sable
fresh sable
cloud dawn
paper sluice
#
class A:
  pass

class B:
  ...
  self.a = 0

class Double(A, B):
  ...

how do i get access to self.a in Double

upper jackal
#
@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

hushed galleon
#

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

upper jackal
#

what should i do know to loop it

cloud dawn
unkempt canyonBOT
#

@cloud dawn :white_check_mark: Your eval job has completed with return code 0.

0
cloud dawn
#

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.

hushed galleon
upper jackal
hushed galleon
#

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)```
frigid pendant
#
    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

calm vector
#

@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).

hushed galleon
#

so would for-looping over a list of ids be acceptable?

calm vector
frigid pendant
#
    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

cloud dawn
#

Okay thanks stelercus.

hushed galleon
upper jackal
#

as i said im pretty new to python

hushed galleon
#

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.

silent ermine
#

would an example of a loop be

@tasks.loop(minutes=1)
async def check_flight():
  time = datetime.datetime.now()
  print(time)

check_flight.start()
somber sky
#

does anyone know how to get a role ID by its name

supple thorn
unkempt canyonBOT
#

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...
supple thorn
#

you could use this

daring olive
fresh sable
#

заебали

#

вот так вот всегда с Украинцами

daring olive
#

!mute 498171366910984193

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @fresh sable until <t:1648608086:f> (59 minutes and 59 seconds).

cloud dawn
daring olive
#

!unmute 498171366910984193

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: pardoned infraction mute for @fresh sable.

daring olive
#

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.

slate swan
#
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,

fresh sable
slate swan
#

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)

slate swan
#

please

fresh sable
final iron
#

What

snow ibex
final iron
fresh sable
#

can i send youtube video ?

slate swan
fresh sable
#

in this channel

daring olive
#

3.0?

slate swan
#

2.0*

daring olive
fresh sable
#

i can help

fresh sable
snow ibex
#

Then don't post it 🙂

fresh sable
#

ok i send in dm

cloud dawn
#

In cmd

fresh sable
#

I just got the same error

#

and fix this

#

Maybe the video I sent him will help him

daring olive
#

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?

nova bear
#

im getting this error and im not sure why

cloud dawn
unkempt canyonBOT
#

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

cloud dawn
#

Please don't advertise here.

fresh sable
loud junco
#

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

daring olive
#

@umbral tapir please read our #rules. while your article is about discord bots, sharing that unprompted is self-promotional

final iron
loud junco
final iron
#

wdym

loud junco
#

i need to keep their progress items

fresh sable
final iron
loud junco
#

i dont think replit has that function

final iron
#

Then don't use replit

loud junco
#

🤦‍♂️

daring olive
#

i mean, isn't there some way with replit?
the progress doesn't necessarily have to permanent like 24/7 right?

daring olive
#

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)

silent ermine
daring olive
#

yeah i've heard of replitdb

cloud dawn
#

replit also allows the useage of sqlite

silent ermine
silent ermine
daring olive
cloud dawn
#

replit db is json based, so using sqlite is actuallt better since it best paired with aiosqlite.

silent ermine
#

Yep

sick birch
#

Discord-related data is best modelled using a relational database, so a relational database might be easier to work with unlike replitdb

final iron
cloud dawn
sick birch
#

I suppose not, but it's not necessarily bad to build up a good infrastructure from the start

silent ermine
round robin
#

whats replitdb

#

i just use mysql its super easy

silent ermine
daring olive
#

i know the downsides

silent ermine
round robin
#

i dont like local file databases

daring olive
#

but if i'm making a personal bot strictly for learning purposes that no one else is gonna use..?

round robin
#

cant be used by mutiple systems and its not as easy to visualize

sick birch
round robin
#

ya

#

i like mysql low ping times

sick birch
silent ermine
round robin
#

7ms to get a row from 5000000 of them

daring olive
#

true. would just run it locally lol

sick birch
#

Exactly

daring olive
#

but just saying "don't use replit" isn't a helpful suggestion

round robin
silent ermine
sick birch
daring olive
#

explain why and give alternatives

round robin
#

thats a option to use that website

silent ermine
sick birch
#

Unless you're using some hacky method like keep alive

silent ermine
sick birch
#

Or uptime robot or whatever

round robin
silent ermine
sick birch
#

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

final iron
silent ermine
#

Heroku nice

sick birch
#

Heroku isn't much better either

final iron
cloud dawn
#

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.

silent ermine
#

What about docker?

sick birch
#

Docker is not a hosting platform

cloud dawn
silent ermine
sick birch
#

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

silent ermine
sick birch
#

That's misinformation

silent ermine
sick birch
#

Anything

silent ermine
cloud dawn
#

You could use it as a db tough. don't recommend

silent ermine
sick birch
#

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

sick birch
#

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

silent ermine
cloud dawn
#

Basically docker is a local vps.

sick birch
silent ermine
sick birch
#

It can run any program in a isolated environment

silent ermine
sick birch
#

Sure you can