#discord-bots

1 messages · Page 1106 of 1

slate swan
#

1hour

sick birch
#

Cool, use the tasks extension

#

Should be relatively easy

slate swan
#
  cursor.execute(f'SELECT * FROM warns WHERE guild_id = {ctx.author.guild.id} and user_id = {member.id}')

here youre referencing member to be a member object which if its not in this case you dont pass the argument it would be None and the NoneType class has no such attribute so you must add a check to make the member argument always a member object so just do this before that line py member = member or ctx.author

#

oh thanks

slate swan
#

❤️

slate swan
slate swan
vale sierra
slate swan
#

it dont work
thats not very descriptive is it?

vale sierra
sick birch
vale sierra
#

oh okkk

vale sierra
#

cursor.execute ?

sick birch
#
cursor = self.bot.db.execute(...)
#

But you have a much larger problem at hand

vale sierra
#

what ?

sick birch
#

You're using sqlite3 as if it were aiosqlite, and using await for statements that don't support it

#

So you need to remove sqlite3, install aiosqlite, and completely migrate over

#

Also you're making a database connection in on_ready() which is a terrible idea

#

This reminds me why I hate using python connectors 😄

vale sierra
#

aiosqlite is way better ?

sick birch
#

No, aiosqlite is the same as sqlite3, except it's asynchronous

#

They're 2 versions of the same thing

vale sierra
#

ok i'll inquire

#

@sick birch just to know, if i move to aiosqlite, my previous code of sqlite3 will be unfonctionnable ?

sick birch
#

That's correct

vale sierra
sick birch
#

That was only a temporary solution, switch over to aiosqlite

slate swan
#
    @discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
    async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        embed = discord.Embed(
            title = "Договор об устройстве на шахту SK",
            color= 0x19ff19
        )
        embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True) 
        embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
        embed.add_field(name=" ", value= " ", inline=False) 
        embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True) 
        embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)

        await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.author.id))

Dear what should be written in iron vacancies class. to pass the ID of the button clicker?

sick birch
#

It's interaction.user.id

vale sierra
sick birch
#

Switching over to aiosqlite is going to require a good bit of rewriting most things related to your database

#

Create your db instance inside your setup_hook

#

Create one by subclassing discord.ext.commands.Bot

slate swan
# sick birch It's `interaction.user.id`
    @discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
    async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        embed = discord.Embed(
            title = "Договор об устройстве на шахту SK",
            color= 0x19ff19
        )
        embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True) 
        embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
        embed.add_field(name=" ", value= " ", inline=False) 
        embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True) 
        embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)

        await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.user.id))
class vacancies_iron(discord.ui.View):
    def __init__(self, id):
        super().__init__()
        self.id = id

    @discord.ui.button( label = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        await interaction.response.edit_message(view=self)
sick birch
#

Bind it to your bot instance (self, inside the subclass) and you should be good

sick birch
slate swan
#

Maybe I wrote something wrong in another class?

sick birch
#

Get rid of the field with no name and no value

slate swan
sick birch
#

Well clearly not

#

Remove it, since there's no point of an empty field

vale sierra
#
async def initialize():
    await bot.wait_until_ready()
    bot.db = await aiosqlite.connect("expData.db")
    await bot.db.execute(
        "CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
``` i put this in my main.py
slate swan
sick birch
#

Just remove the entire line

#

That'll fix it

slate swan
#

I need it to make the second line. without it 3 in one line 1 in the second. or 2 in one 1 in the second and 4 in the 3rd line

sick birch
#

I'm not understanding

potent spear
#

seems like you're trying to add an empty field just to make sure the next field is on a new line

slate swan
#

@sick birchOh it worked. I just thought it wasn't related to a mistake sorry I should have heard it right away. I entered \u200b instead of emptiness

sick birch
#

yeah that works

#

Though i'd stay away from those whitespace characters as they tend to be finnicky and look weird on different devices

slate swan
#

could someone help me out with slash commands please

#
    @discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
    async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        embed = discord.Embed(
            title = "Договор об устройстве на шахту SK",
            color= 0x19ff19
        )
        embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True) 
        embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
        embed.add_field(name="\u200b", value= "\u200b", inline=False) 
        embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True) 
        embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)

        await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.user.id))
    @commands.command(aliases = ["Вакансии", "вакансии"])
    async def vacancies(self, ctx: commands.Context):
        
        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
        embed.set_image(url='attachment://image.png')

        await ctx.send(file = file1, embed = embed, view=vacancies(ctx.author.id))

And can you tell me how to remove the image after pressing the button?

#

Please

vale sierra
potent spear
#

and error says it all, make sure you have bot.db defined in your main file or whatever

vale sierra
# potent spear on_message is an event, not a command
    @commands.Cog.listener()
    async def on_ready(self):
        db = aiosqlite.connect("expData.db")
        self.bot.db = aiosqlite.connect("expData.db")
        await self.bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
        print("DB EXP is Online | Provisoire Message")
``` now i have this error
potent spear
#

don't do shit in on_ready

sick birch
#

Especially not this

potent spear
#

also, connecting in aiosqlite is async if I'm not mistaken

vale sierra
sick birch
potent spear
#

.

#

Not sure if he's on v2

vale sierra
#
async def initialize():
    await bot.wait_until_ready()
    bot.db = await aiosqlite.connect("expData.db")
    await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
``` it is good ?
sick birch
#

If you're not on v2 I personally prefer this method:

async def main():
  bot = commands.Bot(...)
  try:
    # initialize anything else here
    bot.db = ...
    await bot.start()
  finally:
    # cleanup tasks

asyncio.run(main())
vale sierra
#

ok

slate swan
#

you can....

vale sierra
potent spear
sick birch
slate swan
sick birch
#

Ah yeah true, do the startup before

slate swan
#
@discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
    async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        embed = discord.Embed(
            title = "Договор об устройстве на шахту SK",
            color= 0x19ff19
        )
        embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True) 
        embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
        embed.add_field(name="\u200b", value= "\u200b", inline=False) 
        embed.add_field(name="Минимальная оплата труда:", value= f'100 {e_gems}', inline=True) 
        embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)

        await interaction.response.edit_message(embed = embed, view=vacancies_iron(interaction.user.id))
    @commands.command(aliases = ["Вакансии", "вакансии"])
    async def vacancies(self, ctx: commands.Context):
        
        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
        embed.set_image(url='attachment://image.png')

        await ctx.send(file = file1, embed = embed, view=vacancies(ctx.author.id))

tell me Please how to remove the image after pressing the button?

#

it'a better to use a setup_hook though

#

it just looks cleaner

potent spear
#

~on v2

slate swan
slate swan
potent spear
#

is it?

slate swan
#

yep

#

and you should do

async with bot:
   await bot.start(...)
potent spear
#

!d discord.Client.start

unkempt canyonBOT
#

await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect").
slate swan
#

weird

maiden fable
slate swan
#

someone in dpy told me that it's a 2.0 feature fml

slate swan
#

FORGIVE

slate swan
slate swan
sick birch
slate swan
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by editing the original message of a component or modal interaction.
sick birch
#

Use asyncio.run() to call it and replace bot.run(...) with await bot.start(...)

slate swan
potent spear
round knoll
#

someone has a link to an example or template to pull a twitch stream info and post it on discord as a "going live now" notification?

round knoll
#

by info i mean like category (game), stream title etc

sick birch
#

See if twitch has an API for that

round knoll
#

maybe the imbedded image of the game / category being played too

slate swan
#

i have a question, why does discord ascii colored text look trash on mobile?

sick birch
#

Discord code blocks in general look garbage on mobile

slate swan
#

@sick birch@slate swan I love you😍

round knoll
vale sierra
potent spear
#

you can try and read as much info from the member.activities

sick birch
round knoll
#

hmm, alright thanks

sick birch
#

!e

import asyncio

async def another():
  print("I am also an async function :)")

async def main():
  print("I am an async function!")
  await another()

asyncio.run(main())
unkempt canyonBOT
#

@sick birch :white_check_mark: Your eval job has completed with return code 0.

001 | I am an async function!
002 | I am also an async function :)
sick birch
#

Should ideally only be used once

#

Because people are tempted to think of it as a "get out of awaiting coros free card" which it's not

slate swan
sick birch
#

Can't

#

Discord's entire mobile experience is more or less inferior to that on desktop, and there's not much you can do about it

vale sierra
#
async def initialize():
    bot.db = await aiosqlite.connect("expData.db")
    await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")

    asyncio.run(initialize())
potent spear
#

that's inside the function...

sick birch
#

Unindent it, also make sure to actually start your bot

vale sierra
slate swan
#
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image.png")
        embed.set_image(url='attachment://image.png')

        await interaction.response.edit_message(embed = embed, file = file, view=vacancies(interaction.user.id))

🥺 What is not so I do not understand. it worked before

vale sierra
sick birch
sick birch
potent spear
#

not really initializing anymore if you'd ask me

sick birch
#

Yeah call it "main" or something

slate swan
sick birch
#

So pass the simple picture into attachments=[simple_picture]

vale sierra
sick birch
#

It's still inside the function

#

Also your await bot.start() should be last

vale sierra
sick birch
#

Yes, as it's the main thing that starts your entire bot

slate swan
vale sierra
#
bot.loop.create_task(initialize())
bot.start("#")
asyncio.run(bot.db.close())
async def initialize():
    bot.db = await aiosqlite.connect("expData.db")
    await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
    await bot.start()
``` still have the error
sick birch
#

Why are you using asyncio.run() on bot.db.close()?

vale sierra
sick birch
#

No, you use it to run initialize()

vale sierra
#
asyncio.run(initialize())
bot.start("")
await bot.db.close() ``` like this ?
#

@sick birch

sick birch
#

bot.start() should be inside initialize

#

Same thing with await bot.db.close(), should be inside the finally block

vale sierra
#

thats just create me more error and not fixing my error of attribute

sick birch
#

This has gone past fixing errors, it's more of a full project restructuring

vale sierra
sick birch
#

You're on the right track

#

get rid of the last 2 lines though

vale sierra
#

bruh my bot doesnt even launch now

sick birch
#

Do you have your token passed into await bot.start()?

slate swan
#

(((

sick birch
#

Check the docs

vale sierra
#

i dont really understand why i would do that if my error is not fixed thats just make my bot bugging

potent spear
#

well, you've never showed us ANY code of where you're trying to print stuff...

vale sierra
# potent spear well, you've never showed us ANY code of where you're trying to print stuff...
@bot.event
async def on_ready():
    for file in ["tickets_configs.txt"]:
        async with aiofiles.open(file, mode="a") as temp:
            pass

    async with aiofiles.open("ticket_configs.txt", mode="r") as file:
        lines = await file.readline()
        for line in lines:
            data = line.split(" ")
            bot.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]

    print("------------")
    print(f"Prêt ! Bot : {bot.user.name} ")
    print("------------")
    changeStatus.start()
sick birch
potent spear
#

oof txt config

vale sierra
sick birch
#

Yes well, you've already started it

#

Would've been easier to just upgrade to 2.0 and use setup_hook lol

potent spear
#

your choice ofc:
debugging bad implementations
vs
having a good implementation and just never having "strange" errors, since if you're doing it like 99% of the devs, you'll likely get a faster response

sick birch
#

good implementation = easy to fix, predictable errors

vale sierra
potent spear
#

same as in yours 🕰️

sick birch
#

You can leave it off and ping us anytime

slate swan
#

I can't get my len(bot.guilds) to update in the presence of the bot

sick birch
#

Not like we're gonna forget it (probably will but a reminder will probably jog the old brain)

sick birch
vale sierra
vale sierra
potent spear
#

just Western Europe in general

sick birch
#

If you've done exactly as we've said, I believe your code should work just fine with no issues

vale sierra
#

do you want the code ?

slate swan
uncut jacinth
#

I want to make a Info command that shows the badges the user got, But i only have the Hypesquad ids (example:UserFlags.hypesquad_bravery) someone knows the other ones like devs and nitro?

sick birch
#

So just

bot = commands.Bot(...)

async def main():
  bot.db = await aiosqlite.connect(...)
  await bot.db.execute(...)
  await bot.start("token")

asyncio.run(main())
potent spear
sick birch
#

Create a task for it, set it to run on an interval, and do it in there

vale sierra
sick birch
#

odd

slate swan
#

ooooo

vale sierra
#
bot = commands.Bot(command_prefix="+", description="...", help_command=None, intents=Intents.all())
bot.ticket_configs = {}

class Maboulax(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


async def initialize():
    bot.db = await aiosqlite.connect("expData.db")
    await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
    await bot.start("")


# Event

@bot.event
async def on_ready():
    for file in ["tickets_configs.txt"]:
        async with aiofiles.open(file, mode="a") as temp:
            pass

    async with aiofiles.open("ticket_configs.txt", mode="r") as file:
        lines = await file.readline()
        for line in lines:
            data = line.split(" ")
            bot.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]

    print("------------")
    print(f"Prêt ! Bot : {bot.user.name} ")
    print("------------")
    changeStatus.start() ```
slate swan
#

gracias

sick birch
#

Do a print statement in your on ready as the first thing and see if it gets called

vale sierra
#

@sick birch

sick birch
#

And you put it as the first thing and not the last?

vale sierra
sick birch
#

No, the print statement

vale sierra
#

last

sick birch
#
@bot.event
async def on_ready():
    print("Ready worked!") # <-----------------------
    for file in ["tickets_configs.txt"]:
        async with aiofiles.open(file, mode="a") as temp:
            pass

    async with aiofiles.open("ticket_configs.txt", mode="r") as file:
        lines = await file.readline()
        for line in lines:
            data = line.split(" ")
            bot.ticket_configs[int(data[0])] = [int(data[1]), int(data[2]), int(data[3])]

    print("------------")
    print(f"Prêt ! Bot : {bot.user.name} ")
    print("------------")
    changeStatus.start() 
vale sierra
#

dont work

sick birch
#

hmmm

#

that's very odd

#

Can you put a print statement inside your initialize?

vale sierra
#

ah its work

sick birch
#

inside the initialize?

uncut jacinth
#

Someone know the python userflags?

sick birch
#

Can i see just the initialize() function with the print statement?

vale sierra
#
async def initialize():
    print("Hello World")
    bot.db = await aiosqlite.connect("expData.db")
    await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))")
    await bot.start("") ```
#

@sick birchbut for the status its dont work

sick birch
#

Can you also put a print line after await aiosqlite.connect(...)

vale sierra
#

working

slate swan
#
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')

        await interaction.edit_original_message(embed = embed, fille = file1, view=vacancies(interaction.user.id))

I'm too dumb for this job. even the documentation didn't help me💃
help me please

vale sierra
#

@sick birch what should i do for the changeStatus ?

sick birch
#

Is the 2nd print statement working?

vale sierra
#

yes

sick birch
#

Can you put one after await bot.db.execute()?

vale sierra
sick birch
#

Okay.. and one after await bot.start()?

vale sierra
#

don't work

vale sierra
#

@sick birch and for my changeStatus.start() where i can set it ?

sick birch
#

Hmm

#

Right before await bot.start() should work

sick birch
#

mmm

#

try putting it in a cog, and start it in __init__

#

that's how the docs say you should be doing it anyway

vale sierra
#

change nothing, maybe its from the developer portal or idk?

#

@sick birch i'm gonna off, i come back tomorrow, have a good night, tag me if you have news !

sonic flax
#

how would i make a bot save information even after it restarts

slate swan
#

how can i run this as async os.system(f'1.exe convert {cmd_user}.gif')

potent spear
potent spear
sonic flax
potent spear
sonic flax
#

S

paper sluice
#

Imagine discord bots

cerulean folio
#

Hello people !

#

So I upgrade my conda discord env into python 3.10 and suddently import discord.ui ain't working anymore

#

someone has a clue?

fading marlin
#

traceback?

slate swan
#

you need to install the library in that env too, did you?

cerulean folio
#
Traceback (most recent call last):
  File "/main.py", line 3, in <module>
    from discord.ui import Button, View
ModuleNotFoundError: No module named 'discord.ui'
cerulean folio
cerulean folio
dusky pine
#

py -m pip install git+https://github.com/Rapptz/discord.py

#

or if you want to use pycord
py -m pip uninstall discord.py
py -m pip install py-cord -U

cerulean folio
#

I'm confused... what's pycord?

dusky pine
#

you don't need to use it

cerulean folio
dusky pine
#

np

slate swan
#

so you need to reinstall it. ( the library)

slate swan
shrewd apex
#

good morning

cerulean folio
cerulean folio
slate swan
shrewd apex
#

nothing just more studies🥲

#

u can only have one cluster in a free tier right in mongo db

slate swan
#

indeed, on mongodb Atlas

#

server icon ???

#

icon_url and no need to wrap it around a f string!

cerulean folio
#

How can I capture raises for await client.fetch_user(user_id)?

slate swan
slate swan
sick birch
#

i can never forgive discord + uninstalled the app

sick birch
slate swan
sick birch
#

Ah that's a bit better

#

Heroku was meant for web apps right?

slate swan
#

indeed

sick birch
#

Makes sense if you wanna set up a bunch of API routes or whatever to handle interactions on heroku

#

inb4 "but discord officially recommends heroku for hosting bots??? why do you discourage it????"

slate swan
#

the heroku users now have a clear reason: "discord docs suggested me to use it"

sick birch
#

gonna be even harder to explain that it's for interactions through a REST API

#

as opposed to the gateway which is what discord.py does

slate swan
#

yeah, I can't imagine someone using discord.py only for Rest Api, it's meant to be used alongside Gateway

#

works for libraries which actually have a rest based Client though, like that example was for discord.js
hikari and hata in python provides rest too

sick birch
#

interesting, I have to check those out

slate swan
#

lmfao wtf

sullen pewter
slate swan
#

you didn't provide prefix in your commands.Bot object

sacred gull
#

Hey anyone here in who knows how to make a embed creator.

It's basically a custom, cool way to create embeds, all parts are optional besides {embed} as it calls for the embed to be created. It splits variables between $v and && is to show its for the 2nd, optional, part for that variable. This is useful for modules like auto responder or welcome/goodbye messages, where you can have a custom embed response instead of using json.

.ce {embed}$v{title: Embed Title}$v{field: Field Name && Field Content}$v{thumbnail: https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{image:https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{author: This is the author && https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{footer: This is the footer && https://media.discordapp.net/attachments/963615178426056746/963785606431899739/unknown.png?width=628&height=786}$v{timestamp}$v{color: 69ccff}

The output would be:
https://tokyotokyotokyotokyo.tokyo/​‌​‌​​‌​​‌​​‌‌​​​‌‌‌​‌‌​​‌​‌‌​‌​​‌‌​‌‌​​​‌​‌​​‌​​‌​‌​‌‌‌​‌​‌‌​‌​

slate swan
#

seems like a case of regex, use discord modals for these purpose tbh

shrewd apex
#

yeah using modals would be better u wont have the headache for parsing

sacred gull
#

anyone who could help me with it and explain it to me?

#

maybe help me make it, since i have no idea on how to start w it

#

i had a look into modals, but thats not what i want to do

#

i want to do it with parsing

#

hence the code of what i want to get

slate swan
#

Help I'm trying to use .env to store the token and I keep getting these errors. (I'm using the hikari and hikari-lightbulb frameworks)

#

Hey, How do i make my embed color black, like the side line

cerulean folio
#
Traceback (most recent call last):
  File "/home/ayoub/anaconda3/envs/discord/lib/python3.10/site-packages/discord/client.py", line 456, in _run_event
    await coro(*args, **kwargs)
  File "/home/ayoub/dev/personnal/discord_bots/ksf/salus_bot/main.py", line 26, in on_message
    await cmd.add_report(message, client)
  File "/home/ayoub/dev/personnal/discord_bots/ksf/salus_bot/commands/add.py", line 39, in add_report
    await message.channel.send(emb.result(data))
TypeError: 'module' object is not callable

I'm having troubles with importing my code

#

could someone help me with this?

#

In add.py i'm running from .collection import embeds as emb where collection is a folder, in the same directory than add.py.

In collection's __init__.py I have from . import embeds where embeds is a folder in same directory than collection

In embeds's __init__.py I have:

from .constants import EMPTY
from .delete import delete_embed
from .search import not_reported
from .result import result_embed

where all the from are .py files in same dir, and all import are functions inside these files.

#

I don't get what I'm doing wrong :(

shrewd apex
shrewd apex
#

this is the case in class properties

cerulean folio
#

ohhhh i named my embed result

#

i'm stupid

shrewd apex
#

yeah namings can often coz some easy to overlook errors

slate swan
#

how can i like remove a particular amount from wallet and add it to bank?

dusky pine
slate swan
#

json

dusky pine
#

JSON is not a fucking database

#

i will find you and i will hunt you /j

odd mango
#

fr 😂

slate swan
#

:neutral_face:

dusky pine
#

"5 years experience in the JSON NoSQL database"

#

imagine seeing that

slate swan
#

..

odd mango
#

I'll go put that up in my about me

dusky pine
#

JSON is a data interchange format

dusky pine
slate swan
#

drk how can i remove the amount

dusky pine
#

aaaand it's json

slate swan
#

💀 ** **

#

Thats what I said

dusky pine
dusky pine
dusky pine
#

🆗

slate swan
shrewd apex
#

lmao if u want people to stop using json in discord bots make tutorial in yt most people still use swas.py

stone palm
#

guys is there a way (obviously using code) to check whether your bot has been inactive for a long time in a server?

slate swan
dusky pine
shrewd apex
dusky pine
#

someone's gonna make a bot tutorial using XML as a db i'm not gonna be surprised

slate swan
# dusky pine yes

btw
what should i use to check if the amt user sent is more than he is having?

slate swan
stone palm
#

i mean i wanna find the last existing message in the server

dusky pine
slate swan
dusky pine
#

^

#

that's basic conditionals

slate swan
#

💀 ** **

#

amt is a string

#

.
it is a string but what should i do now?

slate swan
slate swan
#

I mean, that was like basic python ¯\_(ツ)_/¯

slate swan
# sonic flax S

whats the purpose of replying to a 3 month old message with a capital S?

paper sluice
slate swan
paper sluice
slate swan
slate swan
#

!ot

unkempt canyonBOT
paper sluice
#

threaten 5 yo

slate swan
#

you can do allot of things with someones public ip

#

ok

pliant gulch
#

when my public ip is dynamic

paper sluice
#

when u dont have ip address

slate swan
#

bro

paper sluice
slate swan
#

..

#

5wpm

#

hi

#

smh

#
@client.command()
async def dep(ctx, *, amt: int):
  await open_account(ctx.author,ctx)

  user = ctx.author

  users = await get_bank_data()

  user_bal = users[str(ctx.author.id)]["wallet"]

  if int(amt) > user_bal:
    await ctx.send("You don't have this amount, don't try to break me.")

  else:
    users[str(ctx.author.id)]["wallet"] -= amt
    users[str(ctx.author.id)]["bank"] += amt

    wallet_amt = users[str(ctx.author.id)]["wallet"]
    bank_amt = users[str(ctx.author.id)]["bank"]
    de = discord.Embed(title=f"{ctx.author.name} deposited {amt}", description=f"Current wallet balance: {wallet_amt} \nCurrent bank balance: {bank_amt}", color=discord.Colour.dark_gray())
    de.set_footer(icon_url=ctx.author.avatar.url)
    async with ctx.typing():
      await ctx.send(embed=de)
``` balance not updated tho
pliant gulch
paper sluice
shrewd apex
slate swan
#

to?

slate swan
paper sluice
slate swan
#

alien spotted

paper sluice
slate swan
#

alien spotted x 2

#

i dont send anything

slate swan
#

i receive everything

#

ur receiver then

paper sluice
slate swan
#

even your log in info

#

it means ur internet

#

smh

slate swan
#

alien gun?

shrewd apex
slate swan
#

sparky you should know arent you an amonger?

slate swan
slate swan
shrewd apex
#

what's an amonger?

slate swan
#

You guys can take this to an off-topic channel, right?

slate swan
#

!ot

unkempt canyonBOT
slate swan
shrewd apex
#

ic

paper sluice
shrewd apex
slate swan
#

ash mad shes not an amonger

#

hi

slate swan
#

:)

paper sluice
# slate swan !ot

you are a shame on society, you are not letting people know about the recent breakthroughs in physics

shrewd apex
#

🤣

slate swan
#

its for research

slate swan
paper sluice
#

sparky's pfp got thanos snapped?

slate swan
#

everyone have anime pfp here 👀

slate swan
#

imagine

shrewd apex
paper sluice
slate swan
paper sluice
#

special creature

shrewd apex
#

lmao even infinity stones dont wanna see him

paper sluice
#

xD

slate swan
#

!e

print(type(()))

sparky is as weird as this

unkempt canyonBOT
#

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

<class 'tuple'>
paper sluice
#

?

slate swan
#

😭 stop bully me

shrewd apex
slate swan
# paper sluice ?

() would just refer to execute it first and if a coma is added it would be a tuple, but if its empty it would be a normal tuple which some users find it weird or confusing lol

#

😑

shrewd apex
slate swan
#

sparky with among us pfp > sparky with no pfp

paper sluice
shrewd apex
#

right one

slate swan
#

^

#

hi

slate swan
dusky pine
#

look it's an amongi

shrewd apex
#

Sparky v 2.0 alive

slate swan
dusky pine
#

plural of among us is amongi

slate swan
#

hes an amonger

shrewd apex
slate swan
#

ok imma change

#

sparky no

dusky pine
paper sluice
#

sparky just got ejected, now hes sad in space

slate swan
#

;-;

shrewd apex
slate swan
#

😳

paper sluice
shrewd apex
slate swan
#

my favorite planet is Uranus

shrewd apex
#

i see why

slate swan
#

because of its size

#

alien spotted

slate swan
#

who likes space here

#

i like astronomy

#

ill ask space questions

shrewd apex
#

ask

slate swan
#

what?

#

its same

#

i know

#

ok

#

so

#

lets move to ot

#

or else mods will mute me 😑

#

ping me

shrewd apex
#

lmao sure just ping there

slate swan
#

Should I use the original dpy for slash commands?

maiden fable
#

Totally your call tbh

slate swan
#

either that, or some fork, or hikari.

#

Is hikari good/

#

anything another than 3rd party libraries

#

I tried it once but it was just too confusing.

slate swan
#

Can you give me some reasons why it is better?

#

I think I am going to get a whole book of features because 3 people are typing together

dusky pine
#

legacy codebase == bad and new codebase == good according to them

#

but it does have a REST thing

#

that's good for dashboards

slate swan
#

What are you talking about...

#

better cache, more native, faster, statically typed ( its totally mypy compatible, multiple command handlers, you can specify how much cache you want to include, better rest implementation, doesn't limit you about what part of Library you can use
and at last, a non toxic helping community

dusky pine
#

it has a command handler?

slate swan
slate swan
dusky pine
#

list one

slate swan
#

!pip hikari-lightbulb

unkempt canyonBOT
slate swan
#

!pop hikari-tanjun

dusky pine
#

damn

slate swan
#

!pip hikari-tanjun

unkempt canyonBOT
slate swan
#

!pip hikari-crescent

unkempt canyonBOT
dusky pine
#

das crazy

#

might consider switching

#

does it have slash cmd support?

slate swan
#

you can even use discord.py views in hikari using hikari-miru 😏

dusky pine
#

!pypi hikari-miru

unkempt canyonBOT
livid hinge
#

what are the main differences between

  • discord.py 1.x
  • discord.py 2.0
  • disnake
    what I have encountered: discord.py 2.0 uses async load_extension, discord.py 1.x comes with message content enabled by defaul, and on disnake you have to add Intents.message_content
slate swan
dusky pine
#

crazy crazy, i'm switching to typescript for my next bot bro 🤯

livid hinge
#

also discord.py 1.x doesnt have some of the ui stuff

slate swan
#

hikari native supports slash and user commands as well

dusky pine
#

what the fuck, hikari native??

slate swan
#

its not a library

dusky pine
#

oh it's just hikari

slate swan
#

native in sense, standalone hikari

#

just like using discord.Client without .ext.commands

livid hinge
#

what is that, a database?

dusky pine
#

i genuinely thought hikari native was like react native for discord bots 🤦

livid hinge
#

oh thats a different thing

slate swan
maiden fable
livid hinge
#

nice, thanks

slate swan
slate swan
#

like sake, a redis cache wrapper built for hikari

#

and some jishaku like stufff

#

hi

livid hinge
#

so not only is the codebase older it also uses an older API version

slate swan
#

yes they are on v8 i think

lyric apex
#

How to check if member is server muted in vc?

maiden fable
#

Smth like member.voice.state

livid hinge
lyric apex
slate swan
#

there was something like that

#

!d discord.Member

unkempt canyonBOT
#

class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").

x == y Checks if two members are equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

x != y Checks if two members are not equal. Note that this works with [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User") instances too.

hash(x) Returns the member’s hash.

str(x) Returns the member’s name with the discriminator.
maiden fable
#

!d discord.Member.voice

unkempt canyonBOT
maiden fable
#

!d discord.VoiceState

unkempt canyonBOT
slate swan
#

..

#

@lyric apex Member.voice.mute

livid hinge
#

maybe, i don't see a date on it ?

slate swan
shrewd apex
#

well good tutorials for dpy bots are rare as diamonds in the rough

maiden fable
livid hinge
#

there are comments from 2 years ago

maiden fable
#

From before v2 was in dev

maiden fable
maiden fable
livid hinge
#

oh, 3 years ago

shrewd apex
#

bruh i used an idiom u go and change that in english dictionaries tell oxford diamonds arent rare

slate swan
#

its from 2019

maiden fable
livid hinge
#

where is that @slate swan

slate swan
#
e = [be1,
         be2,
         be3,
         be4,
         be5,
         be6,
         be7]

    await ctx.send(random.choice(e))

||ofc i didnt send embeds code here||

#

This is what the bot sends

shrewd apex
#

u sure love newlines

slate swan
shrewd apex
#

embed=random.choice()

slate swan
maiden fable
slate swan
livid hinge
maiden fable
#

Yes

slate swan
livid hinge
#

there should probably be a warning that it's 3 years old lmao

slate swan
#

i agree, there should atleast be a "last edited on"

livid hinge
#

can't go based on that alone ig

slate swan
#

all this will no longer be needed as soon as discord.py completes its guide

#

they are working on one

unkempt canyonBOT
#
Missing required argument

code

slate swan
#

Will our bot won't registor slash commands if we don't put test guilds?

#

i am in need of a bot idea

maiden fable
slate swan
#

apparently,it should get registered as soon as the request is made.

short silo
#

To make slash commands global,

Will i have to remove guilds_id

Or

Can I set it to guild_ids=[] or will that make it so commands get registered nowhere ?

slate swan
#

Can we not edit the embed sent by inter.send/

lament mesa
#

but then itll take about 1 hour to register

dim sentinel
#
@spi.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx,amount=5):
    await ctx.channel.purge(limit=amount)
    await ctx.send(f"> :white_check_mark:  The number of messages deleted: {amount}",delete_after=1)
    
@spi.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.MissingPermissions): 
        wa= '> :x:  You do not have `Manage Messages` permission to run this command'
        await ctx.send(wa)  
``` if one error handling works the other doesnt and its vice versa now
#
@spi.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        msg = '> :x: **The command is still on cooldown!**, please try again in {:.2f}s'.format(error.retry_after)
        await ctx.send(msg) 

@spi.command()
@commands.cooldown(1,180,commands.BucketType.user) 
async def ping(ctx,x:str,y:int):
    if y>69:
        await ctx.send("> :x: **The maximum limit is 69** :smirk:")
    else: 
        for i in range(y):
             await ctx.send(x) 
#

this is the other command

#

if one works the other doesnt

slate swan
#
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')

        await interaction.response.edit_message(embed = embed, attachment = ["attachment://image1.png"], view=vacancies(interaction.user.id))

Dear, please tell me how to fix the error?

topaz wraith
#
@spi.command()
@commands.has_permissions(manage_messages=True)
async def purge(ctx,amount=5):
    await ctx.channel.purge(limit=amount)
    await ctx.send(f"> :white_check_mark:  The number of messages deleted: {amount}",delete_after=1)
    
@spi.event
async def on_command_error(ctx, error):
    if isinstance(error,commands.MissingPermissions): 
        wa= '> :x:  You do not have `Manage Messages` permission to run this command'
        await ctx.send(wa)
    elif isinstance(error, commands.CommandOnCooldown):
        msg = '> :x: **The command is still on cooldown!**, please try again in {:.2f}s'.format(error.retry_after)
        await ctx.send(msg)
#

try this

dim sentinel
#

why didnt it work before tho

topaz wraith
#

lol

odd mango
slate swan
slate swan
slate swan
unkempt canyonBOT
slate swan
#

only the discord.Embed object has such an attribute

slate swan
# slate swan only the discord.Embed object has such an attribute
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')

        await interaction.response.edit_message(embed = embed, attachments = ["image1.png"], view=vacancies(interaction.user.id))
    @discord.ui.button( emoji = f"{e_iron}", style=discord.ButtonStyle.primary, row=2)
    async def iron(self, interaction: discord.Interaction, button: discord.ui.Button):
        
        embed = discord.Embed(
            title = "Договор об устройстве на шахту SK",
            color= 0x19ff19
        )
        embed.add_field(name="Ваша должность:", value= "Шахтер", inline=True) 
        embed.add_field(name='Ваше обмундирование:', value='Железная кирка', inline=True)
        embed.add_field(name="\u200b", value= "\u200b", inline=False) 
        embed.add_field(name="Минимальная оплата труда:", value= f"100 {e_gems}", inline=True) 
        embed.add_field(name="График выходов в шахту", value= "4 раза в день", inline=True)

        await interaction.response.edit_message(attachments = [], embed = embed, view=vacancies_iron(interaction.user.id))

Oh, how then to write so that I click on the button below and then on the button above and he sends the picture?

slate swan
# slate swan !d discord.Embed.to_dict

I looked however it asks for 2 arguments. Can you please tell me which one is the second one?

    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')
        embed_dict = embed.to_dict("image1.png")

        embed = discord.Embed.from_dict(embed_dict)
        await interaction.response.edit_message(embed = embed, view=vacancies(interaction.user.id))

#

it only takes an instance of Embed thats all

slate swan
# slate swan it only takes an instance of Embed thats all
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')
        embed_dict = embed.to_dict()

        embed = discord.Embed.from_dict(embed_dict)
        await interaction.response.edit_message(embed = embed, view=vacancies(interaction.user.id))
        await interaction.response.edit_message(embed.to_dict())

It doesn't show the picture.😭

#

because InteractionResponse.edit_message doesnt take any more arguments over an instance of the class InteractionResponse

#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by editing the original message of a component or modal interaction.
slate swan
# slate swan because `InteractionResponse.edit_message` doesnt take any more arguments over a...
    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')
        embed_dict = embed.to_dict()

        embed1= discord.Embed.from_dict(embed_dict)
        await interaction.response.edit_message(embed = embed1, view=vacancies(interaction.user.id))

It now does not give any errors, however, and the picture also does not show. please tell me how to fix it

#

the url of the image youve given is probably invalid

faint void
#

!d help

unkempt canyonBOT
#

help([object])```
Invoke the built-in help system. (This function is intended for interactive use.) If no argument is given, the interactive help system starts on the interpreter console. If the argument is a string, then the string is looked up as the name of a module, function, class, method, keyword, or documentation topic, and a help page is printed on the console. If the argument is any other kind of object, a help page on the object is generated.

Note that if a slash(/) appears in the parameter list of a function when invoking [`help()`](https://docs.python.org/3/library/functions.html#help "help"), it means that the parameters prior to the slash are positional-only. For more info, see [the FAQ entry on positional-only parameters](https://docs.python.org/3/faq/programming.html#faq-positional-only-arguments).

This function is added to the built-in namespace by the [`site`](https://docs.python.org/3/library/site.html#module-site "site: Module responsible for site-specific configuration.") module.
faint void
#

!d events

unkempt canyonBOT
#

IPython Events¶

Extension code can register callbacks functions which will be called on specific events within the IPython code. You can see the current list of available callbacks, and the parameters that will be passed with each, in the callback prototype functions defined in IPython.core.events.

To register callbacks, use IPython.core.events.EventManager.register(). For example:

slate swan
#

#bot-commands .

slate swan
slate swan
slate swan
slate swan
unkempt canyonBOT
#

set_image(*, url)```
Sets the image for the embed content.

This function returns the class instance to allow for fluent-style chaining.
slate swan
#

that's disnake specific.

#

😔

#

so sad

#

they do the same what's being done above, but internally

#

😏 in hikari you can send bytes directly kek

#

im tired, sarth take over🙏

#

((((

    @discord.ui.button( emoji = f"{e_сross}", style=discord.ButtonStyle.red, row=1)
    async def iron_yes(self, interaction: discord.Interaction, button: discord.ui.Button):

        embed = discord.Embed(
            color= 0x19ff19
        )

        file1 = discord.File("./ImageO/Экономика/Work/Выбери Профессию.png", filename="image1.png")
        embed.set_image(url='attachment://image1.png')
        embed_dict = embed.to_dict()

        embed1= discord.Embed.from_dict(embed_dict)
        await interaction.response.edit_message(file= file1, embed = embed1, view=vacancies(interaction.user.id))
#

try files= [file]

#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by editing the original message of a component or modal interaction.
slate swan
#

oh wtf, its meant to be attachments=[file] @slate swan

#

Wow finally working thank you!!!❤️ @slate swan❤️ @slate swan

#

dont thank me

#

thank sarthak🙏

#

ladkiaakhmare lets thank Danny instead

#

lets switch to hikari

#

😼

#

😳 im already in

#

😏

#

trying to make my code mypy compatiable

#

shit_no Optional types are a mess.

#

how so?

slate swan
# slate swan how so?

g_name = bot.get_guild(an_id).name
mypy will shout with

Item "None" of "Optional[Guild]" has no attribute "name"```
#

so you gotta do ```py
if guild:= bot.get_guild(id) is not None:
g_name = guild.name

#

atleast mypy got your back

#

slate swan
slate swan
slate swan
#

the only file im not getting any errors in is your discordheximals looli

#

too good😤

#

jk

#

pithink what should i prefer, normal annotations or string annotations

#

and i found the file of the src

#

its just in a different namespace reason why i couldnt find it

#

and its not in my project folder

#

got this error when using view

slate swan
#

¯_(ツ)_/¯

#
  • __future__.annotations but im asking if i should use it or not
slate swan
#

you didnt pass ctx in it, probably a view?

slate swan
#

it also shouts when i have 2 files with same names cri_till_i_die

#
class search(discord.ui.View):
    def __init__(self, *, timeout=60):
        super().__init__(timeout=timeout)
slate swan
slate swan
#
class searchv(discord.ui.View):
    def __init__(self,context, *, timeout = 60):
        super().__init__(context,timeout=timeout)
        self.add_item(search())
#

yeah, pass the ctx there

slate swan
slate swan
slate swan
slate swan
# slate swan

you would need to pass ctx to the constructor of the instance you have created of searchv

#

and class naming

warm tulip
#

Heyy guys

slate swan
#

Darklight reminds me of someone

#

ashley?

warm tulip
#

Who know how I can make a ti-

warm tulip
slate swan
warm tulip
#

No

slate swan
#

pls continue

warm tulip
#

A command that make a channel for only staff and that person used command

#

Like ticket tool

slate swan
#

!d discord.Guild.create_text_channel

unkempt canyonBOT
#

await create_text_channel(name, *, reason=None, category=None, news=False, position=..., topic=..., slowmode_delay=..., nsfw=..., overwrites=..., default_auto_archive_duration=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates a [`TextChannel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel "discord.TextChannel") for the guild.

Note that you need the [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels "discord.Permissions.manage_channels") permission to create the channel.

The `overwrites` parameter can be used to create a ‘secret’ channel upon creation. This parameter expects a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") of overwrites with the target (either a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") or a [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")) as the key and a [`PermissionOverwrite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.PermissionOverwrite "discord.PermissionOverwrite") as the value.

Note

Creating a channel of a specified position will not update the position of other channels to follow suit. A follow-up call to [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.edit "discord.TextChannel.edit") will be required to update the position of the channel in the channel list...
warm tulip
#

And can you guys tell me how I can set a role permission for a cmd

#

Like warn cmd, every one can use it on my server

slate swan
#

you mean the command author needs that role?

#

to use the command..

warm tulip
#

No

#

Every role have a permission

#

Can't I set a role permission to it?

#

okay_vali_nafahmidam or just a role name

#

Idk

slate swan
slate swan
#

the ctx.send

#

view

#

k

#
@client.command()
async def search(ctx):
  await ctx.send("**Where do you want to search?** \n*Pink an option below to start searching that location!*", view=searchv(ctx))
#

did you remove the ctx param from the view's init?

#

or any changes in the view?..

#

seems like the ctx argument was turned into a kwarg

#

it should look like this ```py
class searchv(ui.View):
def init(self, ctx):
...

white jay
slate swan
#

?

slate swan
#

wait is that pycharm

slate swan
#

making it a Command object which he called and didnt passed any context

slate swan
swift pumice
#

does someone know how i can host my bot 24/7 for free?

slate swan
#

||keep your machine running 24/7|| jk

slate swan
slate swan
shrewd apex
slate swan
#

btw
what does the bot's latency depends on?

slate swan
slate swan
swift pumice
shrewd apex
#

wdym dosent work more likely it's the 2 nd statement

#

either u go for heroku or a vps but a vps still need a computing device

slate swan
#

18 mbps 💀

shrewd apex
#

u need to provide the hardware

shrewd apex
slate swan
#

ig

#

ye

shrewd apex
#

18mbps is fine

slate swan
#

for your bot yes

shrewd apex
#

mine is arnd 50-80 100 at max

slate swan
#

375 is good ig?

shrewd apex
#

mmm slightly slow but fine

#

yeah it will

#

\n is newline character

shrewd apex
#

btw discord phone dosent support ascii

slate swan
#

Btw possible to get all the users who clicked the button and mention them after a while?

shrewd apex
slate swan
#

how?

shrewd apex
#

just put all interaction.user to a list

slate swan
#

mhm

shrewd apex
#

add that in a callback

#

then iterate thru list and ping

slate swan
#

kk

shrewd apex
#

no

#

button has a callback method which u have to use for that

warm tulip
#

Hey guys

#

How I can make a bot send welcome

#

???

slate swan
#

drk what you mean

#

You’ll need to edit the view ig

shrewd apex
#

u will need to edit the view component of the message

#

u can do that by adding the new view choices in the callback of the first menu

#

yeah or viruses wouldnt exist

slate swan
loud osprey
#

idk if this is the right place to ask but Im trying to add twitter functionality to my discord bot, but its api is asking me to enter the keys where would I put my keys? ```python
defaults = {
'enabled': False,
'consumer_key': None,
'consumer_secret': None,
'access_token_key': None,
'access_token_secret': None,

slate swan
#

Just add the view=. . .
Correct me if I’m wrong

#

await interaction.response.send_message(“. . .”, view=. . .)

#

why are you asking this here 💀

loud osprey
#

Wrong place to ask, and yes

shrewd apex
#

depends on what malware it is and its functionalities

slate swan
#

send a message with view on interaction

shrewd apex
#

btw if u are seeing some yt video and asking

#

its most probably wrong info they are giving on that video

#

basically u are wasting ur time

#

put ephemeral=True in ur interaction response

slate swan
#
await interaction.response.send_message(“. . .”, view=view)
#

how are you using the button-

shrewd apex
#

oof that isnt the most effecient way to use buttons

#

discord-components?

slate swan
#

yea

#

U are using these buttons for link(s)

#

Use this ^

#

Requires d.py 2.0 btw

shrewd apex
#

yeah this is fine

#
view = View()
button = Button(details here)
async def callback_here(interaction):
    #call back stuff
button.callback = callback_here
view.add_item(buuton)
await ctx.send(view=view)
#

u can either subclass or just use the in command button defining

#

i mostly subclass either when i am paginating or making menus

paper sluice
#

!d discord.Guild.roles this will return a list of all roles, u can get len from there

unkempt canyonBOT
#

property roles```
Returns a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of the guild’s roles in hierarchy order.

The first element of this list will be the lowest role in the hierarchy.
dim sentinel
#

can ratelimit permanently ban discord bots after certain limit?

swift pumice
#

pls help

slate swan
swift pumice
#
async def verify(ctx, member: nextcord.Member):
        role = nextcord.utils.get(member.server.roles, name='Bauer')
        await ctx.add_roles(member, role)
        await ctx.send(f'{member.name} you are now verified')
    
    ``` why isnt this working?
slate swan
#

instead of server its guild

#

await member.add_roles(role)

swift pumice
slate swan
#
@slash.command(name='userinfo',description="Check user's info", guilds_ids=guild)
async def userinfo(ctx,  member:discord.Member=None):``` Is there a way to add option to this slash command? Btw I use this import `from dislash import *`
slate swan
swift pumice
slate swan
#

yes

#

Cause i dont want to upgrade to v2

slate swan
dim sentinel
slate swan
swift pumice
#
async def verify(ctx, member: nextcord.Member):
        role = nextcord.utils.get(member.guild.roles, name='Bauer')
        await member.add_roles(role)
        await ctx.send(f'{member.name} you are now verified')``` it still isnt working? why
slate swan
slate swan
#

The discussion we're having right now, what does have to do with the question I asked?

paper sluice
slate swan
slate swan
swift pumice
#

thanks

slate swan
slate swan
paper sluice
slate swan
#

^

paper sluice
#

u just have to change the startup and cog setup things, rest is pretty much the same

slate swan
#
@client.event
async def on_guild_update(before, after):
  reason = "Anti Guild Update"
 # guild = after.guild
  logs = await after.audit_logs(limit=1,action=discord.AuditLogAction.guild_update).flatten()
  logs = logs[0]
  await logs.user.ban(reason=f"{reason}")
  await after.edit(name=f"{before.name}")
#

So how to change this into user?

#

@slate swan my bot didn't recover the channel just ban that member

#

Any option ?

#

Auto recovery

#

If anyone creates so many channels at one time but can delete that channel's

#

So you know?

#

Yes

#

why would it require self im not in a cog tho

#

ye

#

got buttons in class

#

i have self in all my methods

#

inside the class

#
@commands.has_permissions(administrator=True)
@commands.command()
async def Recover(ctx):
    for channel in ctx.guild.channels:
        if channel.name in ('rules', 'moderator-only'):
            try:
                await channel.delete()
            except:
               pass 
#

my search command is outside the class but the view is in class

#

How to change this code?

#

Into auto recovery

#

Hi guys, if anyone can help pls

#
class searchv(discord.ui.View):
    def __init__(self,ctx, *, timeout = 60):
        super().__init__(timeout=timeout)
        self.add_item(search(ctx)
``` got this to add the main view
#

search is the view im using for buttons

#

and this class adds it

#
class search(discord.ui.View):
    def __init__(self, *, timeout=60):
        super().__init__(timeout=timeout)
#

view=searchv

#

ye

#

after the content i sent

paper sluice
# slate swan .

self is not related to cogs, its related to classes. when u call a class like classname() ( () calls the class basically ) the class by default passes self arg in the function.
In this case the view searchv is a class and u need to instantiate it

slate swan
#
Traceback (most recent call last):
  File "C:\Users\Infect\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 352, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Infect\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 793, in on_connect
    await self.register_commands()
  File "C:\Users\Infect\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 338, in register_commands
    to_update = update_guild_commands[guild_id]
KeyError: '98748334006193****'

Can anyone help?

#

I added **** cause i didn't wanted the id revealed

#

in the code it's full

maiden fable
#

!d discord.CategoryChannel.mention

unkempt canyonBOT
maiden fable
#

@slate swan ^^^

#

Since that's also a subclass of abc.GuildChannel

slate swan
#

Uh which means?

paper sluice
unkempt canyonBOT
#

@paper sluice :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | KeyError: 3
slate swan
#

well it reads it from Settings.json

settings = json.load(open("settings.json", encoding="utf-8"))

And uses it like this:

settings["guildID"]]

paper sluice
slate swan
nocturne phoenix
#

!projects

unkempt canyonBOT
#

Kindling Projects

The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.

shrewd apex
slate swan
waxen ruin
#

alr quick question, is there a way I can check how long a member has been in a particular server using discord.py? Ty

unkempt canyonBOT
#

An aware datetime object that specifies the date and time in UTC that the member joined the guild. If the member left and rejoined the guild, this will be the latest date. In certain cases, this can be None.

slate swan
#
@slash.command(name='userinfo',description="Check user's info", guilds_ids=guild,options=[Option('title', 'Makes the title of the embed', OptionType.USER)])
async def userinfo(inter,title=None,description=None,user=None):
    user = user or inter.author
    guild = bot.get_guild(944008032042500116)
    user = guild.get_member(user.id)
    if user is None:
        embed = discord.Embed(  
            description = f"** > ⛔ This user is not in this server**",
            colour=0xee0101
        )
        await inter.reply(embed=embed)
    else:
        if user:``` why this doesn't work? When I mention the user in the option, it sends the info of the inter.author and not the user I mentioned
waxen ruin
maiden fable
waxen ruin
slate swan
#

created_at instead of joined_at

waxen ruin
#

alr tysm

waxen ruin
slate swan
#

!d discord.Member.top_role

unkempt canyonBOT
#

property top_role```
Returns the member’s highest role.

This is useful for figuring where a member stands in the role hierarchy chain.
waxen ruin
#

wow, tysm

slim spoke
#

hey, I want to write a code that gets 2 numbers and prints them but if the user didn't give numbers then the numbers will be default but I get an error that the arguments are missing:
discord.ext.commands.errors.MissingRequiredArgument: start is a required argument that is missing.

@client.command()
async def random(ctx,start:int,end:int):
    if not start and not end:
        start = int(1)
        end = int(100)
    print(start,end)
slate swan
#

use default arguments

slate swan
#
@client.event
async def on_guild_update(before, after):
  reason = "Anti Guild Update"
 # guild = after.guild
  logs = await after.audit_logs(limit=1,action=discord.AuditLogAction.guild_update).flatten()
  logs = logs[0]
  await after.guild.ban(logs.user, reason=f"{reason}")
  await after.edit(name=f"{before.name}")
#

await before.ban

slate swan
#

after.ban

#

Only after.ban?@slate swan

#

yea

slim spoke
#

oh got it

#

thank you Sarth

slate swan
#

How can I add numbers in row in front of the user?. E.g 1) @slate swan

#

for row in enumerate(f'{len(role.members)}'): I have this but it doesn't work

slim spoke
#
for row in enumerate(f'{len(role.members),inline = True}'):
slate swan
slim spoke
#

didn't test it on for loop but it works if you put it manualy

#

should work

slate swan
#

doesn't work 🙂

#

The issue is in the arguments

potent spear
#

But you probably want to start from 1, so enumerate(role.members, start=1)

slate swan
#

@slate swan @slate swan

#

well you see the error

#

!d discord.on_guild_channel_delete

unkempt canyonBOT
#

discord.on_guild_channel_delete(channel)``````py

discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.

Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").

This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
slate swan
#

File "main.py", line 676, in on_guild_channel_delete
logs = await before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_delete).flatten()
AttributeError: 'TextChannel' object has no attribute 'audit_logs'

#
@client.event
async def on_guild_channel_delete(before):
  reason = "Anti Guild Update"
 # guild = after.guild
  logs = await before.audit_logs(limit=1, after=datetime.datetime.now() - datetime.timedelta(minutes = 2), action=discord.AuditLogAction.channel_delete).flatten()
  logs = logs[0]
  await before.ban(logs.user, reason=f"{reason}")
  await before.edit(name=f"{before.name}")
#

anyone?

slim spoke
#

I want to upload my bot to github to host it 24/7 but I got this message. I put my token inside a config.json file and then I made a .gitignore.txt file and told it to ignore the config.json.
is it safe to continue?

slim spoke
#

did it now, thanks

slate swan
slim spoke
#

if the repository is private the token won't be leaked?

unkempt canyonBOT
#

async for ... in audit_logs(*, limit=100, before=..., after=..., oldest_first=..., user=..., action=...)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.10)") that enables receiving the guild’s audit logs.

You must have the [`view_audit_log`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.view_audit_log "discord.Permissions.view_audit_log") permission to use this.

Examples

Getting the first 100 entries:

```py
async for entry in guild.audit_logs(limit=100):
    print(f'{entry.user} did {entry.action} to {entry.target}')
```...
slate swan
#

i created channel with my alt and bot did'nt ban me

#

thats why

supple thorn
slim spoke
#

so there is no way hosting the bot 24/7 with github?

shrewd apex
#

it won't ig i did it once b4 and used for a month or so there was no warning

supple thorn
#

But the guild of the textchannel does have it

shrewd apex
#

yeah

supple thorn
#

Yeah

slim spoke
#

I followed a tutorial but Ig I should do more research

shrewd apex
supple thorn
slim spoke
shrewd apex
#

yeah

supple thorn
unkempt canyonBOT
slim spoke
#

okay thankss

slate swan
#

kk

slate swan
#

what's wrong there?

#

wtffffffff

#

Indeed

#

what?

slate swan
paper sluice
slate swan
neat tide
#

In this video, we work on slash command syncing and make a basic slash command with Discord.py, natively. More info below!

If you found this video helpful, please do consider liking the video, subscribing, and sharing it to someone who might find this video helpful (I know a lot of people say this, but it really does help the channel 🙂). If you...

▶ Play video
paper sluice
slate swan
#

I know what the error is

#

buttttttttttttt

shrewd apex
#

eh no

slate swan
#

the @commands must be inside the class

paper sluice