#discord-bots

1 messages · Page 822 of 1

honest vessel
#

fine just fine

ripe steppe
#

good

#

Discord bots one of my favourite things to do with python rn

honest vessel
#

cool

#

I mostly use python for Dbots atm too

ripe steppe
#

what sort of discord bots have you done atm?

honest vessel
#

before it was for irc and skype bots

#

atm my bot keeping track of livestreamers when goes online and alerts and changing activity showing how many are live atm of how many total of streamers in database, and also posts clipped clips from livestreams into a #clips channel - and moderators can add/del streamers and or webradio-stations

#

and it also plays webradios in voicechat (grayzone)

gaunt ice
#

i want to get the message id of the repliedmessage

gaunt ice
honest vessel
cloud dawn
unkempt canyonBOT
#

await reply(content=None, *, fail_if_not_exists=True, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

A shortcut method to [`abc.Messageable.send()`](https://docs.disnake.dev/en/latest/api.html#disnake.abc.Messageable.send "disnake.abc.Messageable.send") to reply to the [`Message`](https://docs.disnake.dev/en/latest/api.html#disnake.Message "disnake.Message").

New in version 1.6.

Changed in version 2.3: Added `fail_if_not_exists` keyword argument. Defaults to `True`.
gaunt ice
honest vessel
#

cause i assume u do like message.reply()

#

or if declared to a variable

cloud dawn
#

Oh you want to get the content of the referenced message?

gaunt ice
cloud dawn
#

Hmm

quick gust
#

!d discord.Message.reference

unkempt canyonBOT
#

The message that this message references. This is only applicable to messages of type MessageType.pins_add, crossposted messages created by a followed channel integration, or message replies.

New in version 1.5.

cloud dawn
#

Was about to type that

gaunt ice
#

but how to use this

honest vessel
#

it is a message object

gaunt ice
#

sry for light mode

dusk dock
#

Is there a way to make slash commands visible to specific users? If so, does anyone know how to do this in disnake?

gaunt ice
quick gust
#

Except editing their perms to use slash commands as a whole

honest vessel
#

There is tho? But i forgot the name let me see

dusk dock
thin kelp
#

Is it possible to get the online status of a user? Like the online, idle and do not disturb thing

honest vessel
#

ephemeral=True

gaunt ice
quick gust
honest vessel
#

oh

thin kelp
#

yeah

quick gust
#

empheral is if the response is visible to a specific user

honest vessel
#

Yeha i read wrong sorry 😦

quick gust
#

!d discord.Member.activity

unkempt canyonBOT
#

property activity: Optional[Union[discord.activity.Activity, discord.activity.Game, discord.activity.CustomActivity, discord.activity.Streaming, discord.activity.Spotify]]```
Returns the primary activity the user is currently doing. Could be `None` if no activity is being done.

Note

Due to a Discord API limitation, this may be `None` if the user is listening to a song on Spotify with a title longer than 128 characters. See [GH-1738](https://github.com/Rapptz/discord.py/issues/1738) for more information.

Note

A user may have multiple activities, these can be accessed under [`activities`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member.activities "discord.Member.activities").
slate swan
#

!intents

unkempt canyonBOT
#

Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. By default, discord.py has all intents enabled, except for the Members and Presences intents, which are needed for events such as on_member and to get members' statuses.

To enable one of these intents, you need to first go to the Discord developer portal, then to the bot page of your bot's application. Scroll down to the Privileged Gateway Intents section, then enable the intents that you need.

Next, in your bot you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

intents = Intents.default()
intents.members = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see the discord.py docs on intents, and for general information about them, see the Discord developer documentation on intents.

quick gust
#

use discord.activity.CustomActivity

#

i think

thin kelp
#

I'll look into it

#

thank you kind sir

slate swan
#

import discord only works too?

quick gust
#

of course

#

u need to pip install it

honest vessel
unkempt canyonBOT
#

property status: discord.enums.Status```
The member’s overall status. If the value is unknown, then it will be a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") instead.
honest vessel
#

oh there u got it

quick gust
#

that's the custom status I believe, on mobile so can't double check

thin kelp
#

One sec

honest vessel
#

its correct

quick gust
#

okay

fresh orchid
#
async def new_restriction():

    for guild in client.guilds:
        for channel in guild.channels:
            print(channel.id, channel.name)

            restriction = await get_restriction()

            if str(channel.id) in restriction:
                     
                return False
            else:
                restriction[str(channel.id)] = {}
                restriction[str(channel.id)]["Moderation"] = 0
                restriction[str(channel.id)]["Scores"] = 0
                restriction[str(channel.id)]["PCC_Content"] = 0
                restriction[str(channel.id)]["Server"] = 0  

            with open("channel_restrictions.json", "w") as f:
                json.dump(restriction,f)
            return True    

I have this code
But when I run it the bot will only "check" and print one channel and then the bot stops

But why
What is wrong with my code?

honest vessel
#

cause you return

fresh orchid
#

i tried without return and its the same

honest vessel
#

maybe you want something like pass

fresh orchid
#

I will try

honest vessel
#

there's pass and continue, break

#

you prob want continue

fresh orchid
#

In my code is there a big difference between pass and continue?

steel void
#

I have multiple casino games how can I make it where a user can't open up more than one game at once?

honest vessel
#

@fresh orchidyou should take look of that link i gave and read about break n continue ignore pass

fresh orchid
#

I read it

Continue will just "stop" the loop at this point and the loop will start again
Bad explanation I know

And pass is just a placeholder and will do nothing

honest vessel
#

and remove returns if you wanna go throu all

#

continue will ignore that one, and keep looping throu list

#

break will stop

#

u can see break as return

fresh orchid
#

so when I use continue it will ignore the json.dump part if its already in the list

And when I use pass it will do the json.dump part but it wont change anything in the file because there is no code to change anythin

#

right?

honest vessel
#

u have a nice example showing you exaclty whats going on with continue

fresh orchid
#

ok thanks for the help I think I got it

honest vessel
#

!e

# Program to show the use of continue statement inside loops

for val in "string":
    if val == "i":
        continue
    print(val)

print("The end")
unkempt canyonBOT
#

@honest vessel :white_check_mark: Your eval job has completed with return code 0.

001 | s
002 | t
003 | r
004 | n
005 | g
006 | The end
honest vessel
fresh orchid
honest vessel
#

i promies your motivation will grow as more you learn - cause that will make it more fun for you

#

and its not C++ and thousands of pages to read

lime trench
#

ok so this is going to be long but i need help normalizing my data. i have a ticket system that when someoine interacts with the persistent button it makes a channel aka the ticket chennal, i want it to be aqble to have commands to show open tickets. i was thinking of making a dict of dicts with the dict key being the channel id and thebn the rest of the info in a dict but im not sure if its good. how should i do it?
list of dicts? dict of list?
im just not sure
sebt here bc its a mix

fresh orchid
#

I tried something like this

client.get_restriction = await get_restriction()

But this will just call the function one time when the code starts and later when I use

self.client.get_restriction

It wont get updated
So I just get the information of the time when the bot started and not the actual

honest vessel
#

why not place the function in a cog and run a task then?

#

if thats ur mission

pliant nacelle
honest vessel
#

in ur code there is no .v commands?

balmy ivy
#

whats the code for the current member count?

slate swan
#

!d discord.Guild.member_count

unkempt canyonBOT
#

property member_count: int```
Returns the true member count regardless of it being loaded fully or not.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be specified.
fresh iron
#
import discord
from discord.ext import commands
client = commands.bot(command_prefix="!")

@client.evevt
async def on_ready():
    print(f"logged in as {client.user}")
    print("ready!")
    print(f"ID: {client.id}")
@client.command()
async def ping(ctx):
    await ctx.send('Pong! {0}'.format(round(client.latency, 1)))

client.run(token)

whats wrong with my code????

#

i keep getting the error import discord even though i have discordpy defined and installed

fresh iron
#

oh

#

right

balmy ivy
#
@bot.event
async def on_member_join(member):
      embed=discord.Embed(title="**__Welcome To GFFL__**", description=":wave: **:partying_face:Hello welcome to the League** **Have Fun** :scroll:`Make sure to go follow the rules everything is listed in information ` ", color=0xe0e0e0)

      await member.send(embed=embed)```
slate swan
#

another thing, make sure python is added to path

balmy ivy
#

where would i put the current member count

#

so like

slate swan
#

member.guild.member_count will be the member count

honest vessel
#

well were u wanna display it

fresh iron
balmy ivy
#

Welcome you are our <current member>

honest vessel
#

then put it there

slate swan
fresh iron
#

it is added to path

slate swan
#

oh, are you using vscode?

fresh iron
#

yes?

honest vessel
#

I have been told not to spoonfeed so

cold sonnet
#

do you have multiple versions of python installed?

honest vessel
#

title="Welcome To GFFL" how can u include a variable into a string?

slate swan
#

if you installed the library just now, restart it
dont use the play button to run the code, download the python extension and use the run option above to run your code, you can confirm your python installation there

pliant nacelle
fresh iron
#

the code doesnt work with or without vscode

#

ill try to run it online

honest vessel
#

@pliant nacellei dont know most annoying shitty code iv ever seen doing a discordbot

#

one asked tho what lib u using

pliant nacelle
honest vessel
#

lol?

slate swan
honest vessel
#

it looks like a homebrewed

#

not a real lib

#

raw api?

#
import functions as func
from commands.base import Cmd

help_text = [
    [
        ("Usage:", "<PREFIX> <COMMAND> `NEW NAME`"),
        ("Description:",
         "Directly change the name of the channel you're in. "
         "Supports all variables from the `template` command (use `<PREFIX> help template` to get a list).\n\n"
         "Use `<PREFIX> <COMMAND> reset` to remove your name override and revert to the original template."),
        ("Examples:",
         "<PREFIX> <COMMAND> Bob's bustling barbeque bash\n"
         "<PREFIX> <COMMAND> Karen loves @@game_name@@\n"
         "<PREFIX> <COMMAND> reset"),
    ]
]


async def execute(ctx, params):
    params_str = ctx['clean_paramstr']
    guild = ctx['guild']
    author = ctx['message'].author

    new_name = params_str.replace('\n', ' ')  # Can't have newlines in channel name.
    new_name = new_name.strip()
    if new_name:
        return await func.custom_name(guild, ctx['voice_channel'], author, new_name)
    else:
        return False, ("You need to specify a new name for this channel, e.g. '{0}name <new name>'.\n"
                       "Run '{0}help template' for a full list of variables you can use like "
                       "`@@game_name@@`, `@@creator@@` and `@@num_others@@`.".format(ctx['print_prefix']))
``` where is import discord?
#

kek

pliant nacelle
#

not in this file

honest vessel
#

no shit sherlok 😄

#

verry confusing codes

slate swan
#

show the commands/base.py file @pliant nacelle

honest vessel
#

and functions

#

return await func.custom_name(guild, ctx['voice_channel'], author, new_name)

slate swan
#

they do it like that

honest vessel
#

it looks absolutely shit all i can say

#

@slate swanso a js with pywrapper

#

why???

slate swan
#

!pip discord.js

unkempt canyonBOT
honest vessel
#

omg

slate swan
honest vessel
#

why thoi?

#

"i wanna code JS but in python"

slate swan
#

idk maybe someone said, discord.js has better Object attributes than discord.py and he just made it to prove them wrong

honest vessel
#

lol

#

i feel sick

slate swan
#

well yea for some things , like js Guild.iconURL({dynamic: true/false}) it allows users to choose weather to return the animated or static version

honest vessel
#
from discordjs import Client
from javascript import console

client = Client()

client.on("ready", lambda:
    console.log("Bot is ready")
)

async def msg(message):
    if message.content.startswith("!ping"):
        await message.channel.send("pong")

client.on("message", msg)

client.login('Token')
``` then go code in JS
slate swan
#

discord.js' kinda bettter with these things

honest vessel
#

for what?

honest vessel
#

cant they use a js lib already?=

slate swan
#

ofcourse, "but python is easy"

honest vessel
#

is python easy that way?

#

thats jsython

slate swan
honest vessel
#

if u code js code js, thats fine ... but i dunno its like write chinese but wanna speak swedish with a indien accent taste of japan

#

u need to code js to understand that lib

honest vessel
#

ye

slate swan
maiden fable
#

Well I tried coding with it once...

honest vessel
maiden fable
#

When I got started, I started thinking, "Python is way better in terms of simplicity as compared to JS"

slate swan
maiden fable
#

So yea, I got mad because I wasn't able to understand when to use === and when to use == lmao

honest vessel
#

so you didnt wanna convert your religion from py to js

maiden fable
honest vessel
#

one think js had as fresh n shit well handy was Objects aka Arrays

slate swan
#

some person who used js teached me how to make objects in python ```py
_object = {'attr':'value'}

maiden fable
#

I mean, why add another keyword to subclass LMAO

#

Python is just too simple and readable haha

honest vessel
#

python is clean

#

no brackets or anything

slate swan
#

it has cons tho

honest vessel
#

but imagine write pythong and put js brackets on lol

balmy ivy
#

how could i do this

slate swan
#

!d discord.Embed.add_field

unkempt canyonBOT
#

add_field(*, name, value, inline=True)```
Adds a field to the embed object.

This function returns the class instance to allow for fluent-style chaining.
honest vessel
buoyant quail
#

++

maiden fable
#

Lmao

honest vessel
#

nothing was super excotic about that embed

maiden fable
#

Well there is a probability they are new to discord bot making

honest vessel
#

then its a py server

#

why use jswrap

#

they misled

#

how i make discordbot like this? shows embed coded in asm

visual yarrow
honest vessel
#

@visual yarrowhe could specify Q more

fresh iron
honest vessel
#

it only display an embed

cold sonnet
#

@fresh iron do pip install discord.py once more and show us the results

daring olive
maiden fable
slate swan
# fresh iron

do you have multiple versions of python installed?

visual yarrow
fresh iron
cold sonnet
#

I forgot already

maiden fable
honest vessel
slate swan
cold sonnet
maiden fable
maiden fable
honest vessel
fresh iron
cold sonnet
maiden fable
#

Haha

slate swan
cold sonnet
maiden fable
# fresh iron

Told ya, most probably wrong Python version selected

daring olive
cold sonnet
fresh iron
#

everything was fine yasterday not sure whats changed now

honest vessel
maiden fable
#

Well most probably yr Python version in yr IDE changed @fresh iron

slate swan
lethal umbra
slate swan
slate swan
cold sonnet
#

I looked at the wrong line

honest vessel
#

@daring olive @visual yarrow u give me another chance?

slate swan
visual yarrow
cold sonnet
#

@fresh iron

fresh iron
#

oh

slate swan
#

install the python installation as told ya already

honest vessel
maiden fable
slate swan
#

if you did and its still not coming , use ctrl+shift+p and type select interpreter

fresh iron
balmy ivy
slate swan
fresh iron
#

it is installed

honest vessel
#

if u want an int of how many

balmy ivy
slate swan
# pliant gulch I'm gonna blame toxickids!

🏃‍♂️ i was sick trying to install it with that command until i realised it missed the :
well imma try looking into the internals to get familiar with the library and may make some contributions :)

fresh iron
slate swan
#

and how did you run the code?

honest vessel
#

@balmy ivyall i see is 1 user and alot of new fields

#

in an embed

fresh iron
honest vessel
#

add_field()?

fresh iron
#

from run?

slate swan
# fresh iron

use the run option above in near file and other options

honest vessel
#

embed.add_field() and inline=False, or If want True?

balmy ivy
#

no ik add field but i am saying like you can use -members <role> and lists all the members that have the role

slate swan
#

or just hit ctrl+f5

balmy ivy
#

but i want it to be only 32 roles

balmy ivy
#

so that members see how many members are on that role

fresh iron
#

that's what i literally do though it gives the same error, might just reinstall everything

honest vessel
#

you def can do

slate swan
#

the play button is broken

balmy ivy
fresh iron
#

ill reinstall python

honest vessel
#

@balmy ivytrying to figure out but should be around guild.roles and go from there

slate swan
#

ctrl+f5 still results with the same error?

fresh iron
#

yeah it's literally the same

honest vessel
#

Role object has members attribute @balmy ivy

#

so fetch role and grab .members

balmy ivy
#

@bot.command()
async def members(ctx):

honest vessel
#

and len() members attribute

#

no

fresh iron
#

i just noticed i shared a token lmfao

maiden fable
#

👀 Why I wasn't here

honest vessel
#

fetch role you want to check of how many users, and then you have Role = fetched....
count = len(Role.members)

fresh iron
#

feel free to use that bot its made by an alt

honest vessel
#

@balmy ivy u wanna len() that members

honest vessel
#

omg

balmy ivy
#

just sent it all in one

honest vessel
#

fetch a guild role

slate swan
#

or get_ it actually

honest vessel
#

and len() the role.members

#

object

honest vessel
balmy ivy
honest vessel
#

its true others complain if i do it

balmy ivy
honest vessel
#

no Role needs to be grabbing an role object from that guild

#

and then len() on that role object with attribute members

crude spear
#

how can i add that the user can just use the command between different time examples just from 10am until 3pm

balmy ivy
cold sonnet
#

import datetime

honest vessel
#

@balmy ivyeither way tbh, but hint guild.get_role()

cold sonnet
#

and check if datetime.now() is above 10am and under 3pm

balmy ivy
#

wait so replace role =() with guild.get_role()

fresh orchid
honest vessel
#

in that guild

#

guild.get_role() i think

#

with id or name

balmy ivy
#

ok but len(Role.members) has a error when i use guild.get_role()

honest vessel
#

i would recommend use ID instead of name cause if u wanna change name of role its broken

vale wing
fresh orchid
vale wing
#

For the first method, just define a function in a separated file and import it from there whenever you need it, for the second just define it in your bot's subclass

rocky trench
#
        mutedRole = discord.utils.get(ctx.guild.roles, name="Muted")
        if not mutedRole:
            index = 0
            for role in ctx.guild.roles:
                if role.permissions.administrator:
                    index += 1
            index -= 1
            mutedRole = await ctx.guild.create_role(name="Muted")
            await mutedRole.edit(reason = None, position = index)```no error, doesnt drag it to the right position
vale wing
#

What do you want it to do

#

And why use muted role when timeout exists

balmy ivy
#

how could i make a command where it shows how many people on a role

vale wing
#

!d discord.Role.members

unkempt canyonBOT
balmy ivy
vale wing
#

Just use len on it

balmy ivy
vale wing
#

!e py some_list = [1, 2, 3, 4, 5] print(len(some_list))

unkempt canyonBOT
#

@vale wing :white_check_mark: Your eval job has completed with return code 0.

5
balmy ivy
vale wing
#

May I ask what is your python experience level

balmy ivy
vale wing
balmy ivy
#

sum like this

vale wing
#

I will not write the full command for you lol, this is enough help I'd say. The docs are pretty useful

balmy ivy
vale wing
#

I just don't get what you don't understand, if you told me I could've helped you probably

#

Also you haven't answered my question about your python knowledge properly

vale wing
#

Just in case it is low, the discord bot is not a good beginner project

#

You need decent knowledge of python to understand what you do

#

On the other hand, if you consider yourself experienced enough you may check this tutorial out https://vcokltfre.dev

A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.

balmy ivy
#

i already know how to use embeds and make like a help command

vale wing
#

Yea but do you know how to iterate through the list and get attributes of an object

#

That's all you need for members command

#
  • some docs, to be more exact discord.Role and discord.Member
rocky trench
slate swan
rocky trench
#

I've seen some really bad ones, mb

final iron
rocky trench
stray solar
#

Hello... someone have some time to help to make a trigger author message delete ?

#

(User sent a message, bot automatically delete the current message who the user sent)

bitter perch
rocky trench
#

it was an example

#

even though I make my own help commands

#

since I never learnt on how to style a built in one

bitter perch
#

!docs discord.ext.commands.HelpCommand

unkempt canyonBOT
#

class discord.ext.commands.HelpCommand(*args, **kwargs)```
The base implementation for help command formatting.

Note

Internally instances of this class are deep copied every time the command itself is invoked to prevent a race condition mentioned in [GH-2123](https://github.com/Rapptz/discord.py/issues/2123).

This means that relying on the state of this class to be the same between command invocations would not work as expected.
slate swan
stray solar
#

When i do the command trigger (+trigger <id>)
the bot will delete every message the user sent
so if he send a msg, the bot will delete the msg automatically with 1 ms

#

So i did @bot.command() async def trigger(ctx, message, author): await ctx.message.delete list_of_ids.append(author.id) if author.id in list_of_ids: await message.delete() await asyncio.sleep(0)

#

But i get discord.ext.commands.errors.MissingRequiredArgument: author is a required argument that is missing.

slate swan
#

Okay my eyes gonna bleed

stray solar
#

Im beginner xd

fresh orchid
#

Im not sure if this is the right channel but I have this code

    @commands.command()
    async def whois(self, ctx, member:discord.Member = None):
        await check_server_restriction(ctx)
        await ctx.send("CONTENT")

The check_server_restriction looks like this

async def check_server_restriction(ctx):
    restriction = await get_restriction()
    
    if restriction[str(ctx.channel.id)]["Server"] == 1:
        await ctx.send("This command is restricted. You can use it in the #bot-commands channel")
        return

So when I run it it sends the this command is restricted text but the other CONTENT too

I dont get why because my code says after the bot sends the this command is restricted it should return

So why it sends the content too and ignores the return

fresh orchid
stray solar
#

Imma try

fresh orchid
#

there is no error

slate swan
#

Wrong reply

slow fog
fresh orchid
#

as I said it just send both things

sacred reef
#

hi, i have a question. i have a @task.loop and i want to run it through async. problem is, whenever i try to await it start. it runs but whenever i try to do it again, it just wont run the task seperately

basically i wanna run 2 tasks at the same time

fresh orchid
#

and I dont know why because there is a return

sacred reef
#

and it doesnt seem that possible for me

slate swan
slow fog
#

but

#

youre sus

slate swan
fresh orchid
#

oh ok

slate swan
stray solar
analog barn
#

hey, I'm making a discord bot, but I want to be able to run it with arguments.
I've tried looking into sys.argv and argparse but nothing is working for me right now. I think because discord.py is asynchronous but I don't know for sure if that's even remotely close to why I can't get it to work... anyone able to help?

fresh orchid
slate swan
stray solar
#


@bot.command()
async def trigger(ctx):
    await ctx.message.delete
    list_of_ids.append(ctx.author.id)
    if ctx.author.id in list_of_ids:
        await ctx.message.delete()
        await asyncio.sleep(0)```
#

Thats my actual code now

vale wing
#

Where the brackets for delete()

slate swan
#

Why even make a conditional when its gonna append it to the list in the first place

vale wing
#

And wtf is asyncio.sleep(0)

#

Like why'd you need to wait for 0 seconds

stray solar
#

bcs its the logic of trigger message

vale wing
final iron
stray solar
#

when the trigger user send a msg, i want the bot automatically del the msg

#

so i did 0 ms

vale wing
final iron
#

Then use an on_message

#

!d discord.on_message

unkempt canyonBOT
#

discord.on_message(message)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/master/api.html#discord.Message "discord.Message") is created and sent.

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

Warning

Your bot’s own messages and private messages are sent through this event. This can lead cases of ‘recursion’ depending on how your bot was programmed. If you want the bot to not reply to itself, consider checking the user IDs. Note that [`Bot`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.Bot "discord.ext.commands.Bot") does not have this problem.
stray solar
#

on message make my bot crash

#

thats why i want to do a command

final iron
#

That's a whole nother issue

stray solar
#

a friend made the same with c# command

#

so i wanted to do the same with py

sacred reef
# vale wing Can you show your code

its pretty long, messy since i didnt expect anyone else to see it. it has nothing to do with the code but ill show you the important parts

@tasks.loop(seconds=30.0)
async def plant_growth(self,ctx,trayid,number):
await plant_growth.start(self, ctx, trayid, number)
vale wing
#

@stray solar you might want to check this tutorial out, it seems like you missing normal resources https://vcokltfre.dev

A tutorial on how to use discord.py to create your own Discord bot in Python, written to fix the flaws of many other popular tutorials.

vale wing
sacred reef
#

realy?

#

really?*

vale wing
#

You don't parse args to it do you? I never did so idrk

sacred reef
#

you can

vale wing
#
@tasks.loop(seconds=30)
async def some_loop(self):
    pass #stuff

#and this is in some cog init
some_loop.start()```
#

The start surely doesn't need to be awaited and you don't parse self that's for sure

#

Gotta check docs about other things

sacred reef
#

mk

#

ill try it

vale wing
#

!d discord.ext.tasks.loop

unkempt canyonBOT
#

discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, loop=...)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/master/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
vale wing
#

Where do you start it

#

Is it in a cog?

sacred reef
#

when i run a command, and yes

vale wing
#

You typically don't start loops from a command

#

Can you tell me what are you trying to make

sacred reef
#

im trying to basically randomly simulate 4 trays with different plants in them, and i run the command to start the plant growth

rocky bluff
#

hey

sacred reef
#

i want to run the same task for 5 different trays

vale wing
rocky bluff
#

how could i make a command where it takes everyone off a role? like -disband <emoji>

pine crypt
#

Why does this give the error message:

stray solar
#

Why client ?

vale wing
pine crypt
#

as in $ping client?

vale wing
#

Yes

pine crypt
sacred reef
vale wing
#

Well seems like you are doing something wrong

#

Could you show the whole command

#

You probably want the latency of the bot

#

And show cog init as well please

pliant gulch
#

There is no reason for you to have client as an argument here. You want to do self.client or whatever your client is defined as in the cog

pliant gulch
#

Yea, so use self.client when using the latency

#

Instead of client

pine crypt
sacred reef
pine crypt
#

ah ty 🙂

sacred reef
#

np

pine crypt
# sacred reef np

Since in the init i have defined self.client as client then why should self.client be used instead of client?

sacred reef
pine crypt
sacred reef
#

there

vale wing
#

The self refers to the class object

sacred reef
#

ok there

pine crypt
vale wing
#

You didn't remove client from command args

sacred reef
#

^

pine crypt
#

ty

placid skiff
#

Whi this:

class NoInviteFound(CheckFailure):
    super().__init__(message="This user has no invites")
  File "C:\Users\giacomo.dimatteo\PycharmProjects\ZhagoBot\lib\bot\invites_check\Checks.py", line 11, in NoInviteFound
    super().__init__(message="This user has no invites")
RuntimeError: super(): no arguments
vale wing
#

This should be inside of __init__ lol

placid skiff
#

i'm stupid D_D

balmy ivy
#
async def bold(ctx, text):
  ff.boldTEXT(text)
  await ctx.reply(text)

  text = text.replace("a", "𝗮")
  text = text.replace("b", "𝗯")
  text = text.replace("c", "𝗰")
  text = text.replace("d", "𝗱")
  text = text.replace("e", "𝗲")
  text = text.replace("f", "𝗳")
  text = text.replace("g", "𝗴")
  text = text.replace("h", "𝗵")
  text = text.replace("i", "𝗶")
  text = text.replace("j", "𝗷")
  text = text.replace("k", "𝗸")
  text = text.replace("l", "𝗹")
  text = text.replace("m", "𝗺")
  text = text.replace("n", "𝗻")
  text = text.replace("o", "𝗼")
  text = text.replace("p", "𝗽")
  text = text.replace("q", "𝗾")
  text = text.replace("r", "𝗿")
  text = text.replace("s", "𝘀")
  text = text.replace("t", "𝘁")
  text = text.replace("u", "𝘂")
  text = text.replace("v", "𝘃")
  text = text.replace("w", "𝘄")
  text = text.replace("x", "𝘅")
  text = text.replace("y", "𝘆")
  text = text.replace("z", "𝘇")

  text = text.replace("A", "𝗔")
  text = text.replace("B", "𝗕")
  text = text.replace("C", "𝗖")
  text = text.replace("D", "𝗗")
  text = text.replace("E", "𝗘")
  text = text.replace("F", "𝗙")
  text = text.replace("G", "𝗚")
  text = text.replace("H", "𝗛")
  text = text.replace("I", "𝗜")
  text = text.replace("J", "𝗝")
  text = text.replace("K", "𝗞")
  text = text.replace("L", "𝗟")
  text = text.replace("M", "𝗠")
  text = text.replace("N", "𝗡")
  text = text.replace("O", "𝗢")
  text = text.replace("P", "𝗣")
  text = text.replace("Q", "𝗤")
  text = text.replace("R", "𝗥")
  text = text.replace("S", "𝗦")
  text = text.replace("T", "𝗧")
  text = text.replace("U", "𝗨")
  text = text.replace("V", "𝗩")
  text = text.replace("W", "𝗪")
  text = text.replace("X", "𝗫")
  text = text.replace("Y", "𝗬")
  text = text.replace("Z", "𝗭")
  
  text = text.replace("|", "┃")
  text = text.replace("-", "━")```
#

why wont this work

#

it says ff is a error

bitter perch
slate swan
#

example on how to use a dict

en = {
    'a': '>',
    'b': '?',
    'c': '*',
    'd': '-',
    'e': '+',
    'f': '^',
    'g': '%',
    'h': '@',
    'i': '!',
    'j': '$',
    'k': '_',
    'l': '`',
    'm': '~',
    'n': 'c',
    'o': '|',
    'p': '}',
    'q': '[',
    'r': ')',
    's': '{',
    't': ']',
    'u': '(',
    'v': '=',
    'w': ';',
    'x': ':',
    'y': ',',
    'z': '.',
    '1': '"',
    '2': 'j',
    '3': 't',
    '4': 'k',
    '5': 'b',
    '6': 'd',
    '7': 'l',
    '8': 's',
    '9': 'a',
    ' ': ' ',
    '.': '.',
    ',': ','
    }

def encrypt():
    text = input("\nWhat text would you like to encrypt:\n")
    print(f"\nYour encrypted text looks like:\n{''.join([en[l] for l in text.lower()])}")

encrypt()

dumb little thing i made lol

slate swan
#

i said it was an example you use the dict so it will return the key

balmy ivy
#

no i am saying thats not what i am using

slate swan
#

you want to replace each letter with its font counter part right?

balmy ivy
#

i am trying to do this

balmy ivy
slate swan
#

yes im correct?

balmy ivy
slate swan
#

its bold

#

a bold font

slate swan
#

||example||

balmy ivy
#

bro is that bold or not

slate swan
#

its an example bro

#

What are you doing

#

and why not use the built in bold feature discord provides?

#

its the same thing

slate swan
balmy ivy
slate swan
#

so any text you add no matter if it has invalid chars it will make them bold and you will not be limited by chars*

slate swan
balmy ivy
#

ok?

slate swan
#

why not use the code i gave you can make any sentence bold and youre not limited to chars

#

?

slate swan
#

did it worked?

balmy ivy
#

yea

slate swan
#

are you satisfied?

balmy ivy
#

yea

slate swan
#

great

balmy ivy
#

thanks

slate swan
#

yw

balmy ivy
#

𝗭

#

Z

#

when i used the first letter it does this

#

in channels

balmy ivy
slate swan
slate swan
#

yes but replace the keys and values

balmy ivy
#

whats the point i just wanna know how to fix my code i will just spend more time

slate swan
#

well your code wont work

#

your code will replace

text = text.replace("-", "━")
balmy ivy
#

like this but not using **

final iron
#

Why though

#

You have to hardcode all of the characters

#

Also why is your prefix /

#

That's so annoying to use

oblique laurel
#

Not an issue if theyre fine w it

final iron
#

It's dumb though

slate swan
#

i need help with anti nuke

final iron
#

What specifically

slate swan
#

the whole thing @final iron

final iron
#

Anti nuke is quite complicated

#

You need to decide what you want to trigger it and how to handle it

slate swan
#

or something

final iron
#

You want to prevent server invites?

slate swan
#

yes

#

or something kinda like haunt and bleed

#

like antiraid

placid skiff
#
@slash_command(name="accept_reaction", guild_ids=[865691556736008213])
    @has_permissions(administrator=True)
    async def accept_reaction(self, ctx: ApplicationCommandInteraction, emoji: str):
        emoji: Emoji = self.bot.get_emoji(int(emoji))
        if emoji is not None:
            await ctx.send(f"L'emoji {emoji.name} è stata impostata", ephemeral=True)
            db.execute("UPDATE Guild SET InvitesEmojiID = ? WHERE GuildID IS ?", emoji.id, ctx.guild.id)
        else:
            await ctx.send("Emoji non trovata", ephemeral=True)

It gives me None, someone knows why?

dire folio
#

does anyone know how to use the Discord-Anti-Spam package

manic wing
desert badger
#

Is anyone here ok with disnake ? bananacat

dire folio
#

most people here use disnake

desert badger
#

cuz my button doesnt work anyone after i restart my client :(

#

and i wanna know how to fix that

#

heres my code

class VerifyButton(disnake.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @disnake.ui.button(label="✅ Verify", style=ButtonStyle.green, custom_id="verify")
    async def verify_button(self, button: disnake.ui.Button, interaction: disnake.MessageInteraction):
        role = interaction.guild.get_role(838801845530919002)
        if role in interaction.user.roles:
            embed = disnake.Embed(
            title = "You are already verified!",
            color = disnake.Color.red()
        )
            await interaction.response.send_message(embed = embed, ephemeral = True)
            return
        await interaction.user.add_roles(role)
        embed = disnake.Embed(
            title = "You have successfully verified!",
            color = disnake.Color.green()
        )
        await interaction.response.send_message(embed = embed, ephemeral = True)
        return
``` hope anyone can help ![bananacat](https://cdn.discordapp.com/emojis/909487499632607322.webp?size=128 "bananacat")
pliant gulch
jovial pilot
#

What amount of code knowledge should i have before starting to make a discord bot

pliant gulch
manic wing
#

andy

#

are you pals with danny

pliant gulch
#

No

manic wing
#

how come

pliant gulch
#

I've never spoken to him

placid skiff
manic wing
balmy ivy
#

i have this error whats wrong?

#

anyone help?

heavy folio
# slate swan yes

on_message > check if the message content ```py
r"(?:https?://)?discord(?:app)?.(?:com/invite|gg)/[a-zA-Z0-9]+/?"

bitter perch
serene mantle
#

Hey guys, im coding a Discord bot, and i need to add a role to a user upon a message event.

#

i found this on stackoverflow

#
var = disnake.utils.get(message.guild.roles, name = "12")
member.add_role(var)```
#

"12" is the name of my role

#

message.guild.roles simply does not exist.

supple thorn
#

Guessing thats a age role

slim ibex
#

copying code from stack overflow like all devs 🗿

serene mantle
#

xD

#

LMAO

serene mantle
#

No its just a placeholder, since you can't mispell 12 lol.

serene mantle
#
                        member = message.author
                        var = disnake.utils.get(message.guild.roles, name = "12")
                        member.add_role(var)```
#

full code any one know whats wrong

supple thorn
#

Where is this code

serene mantle
#

on my screen?

supple thorn
#

In a command or?

serene mantle
#

oh lol

#

on_message event

supple thorn
#

Okay

supple thorn
serene mantle
#
  File "c:\Users\giftc\OneDrive\Desktop\Python\Discord Bot\cogs\verfication.py", line 70, in on_message
    print(message.guild.roles)
AttributeError: 'NoneType' object has no attribute 'roles'```
#

also i tried printing message.guild.roles

#

it doesnt exist, but all solutions online include it

serene mantle
#

it prints None

#

OHHH

#

i think i know whats going on rn

supple thorn
#

Wait

serene mantle
#

gimme a sec

supple thorn
#

I do too

#

@serene mantle its in dms isnt it

#

I just read your python file name

serene mantle
#

omg

#

sorry for bothering you lol

#

im literally half asleep lmao

supple thorn
#

I was gonna ask if its in dms or not but wanted to make sure

serene mantle
#

it is in DM's lol

#
                        server_id = 932378633463562290
                        print(server_id.guild)```
#

this doesnt work either lol

heavy folio
#

server_id.guild? yert

final iron
serene mantle
#

all these results are very outdated im finding

#

trying to take a new approach.

final iron
serene mantle
#

yeah, i know im just trying everything i can think of

#

this is what i have currently

#
                        the_role = disnake.utils.get(942138061792378931)
                        await message.author.add_roles(the_role)

#

this gives me the error

  File "C:\Users\giftc\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\utils.py", line 480, in get
    for elem in iterable:
TypeError: 'int' object is not iterable```
#

942138061792378931 is the Role ID

#

this is a on_message event btw

gaunt ice
kind wasp
#

Hello i need to know, have any difference between discordpy and disnake?

slate swan
gaunt ice
#

yes nearly nothing

slate swan
kind wasp
#

Thx so much ;)

slate swan
#

theirs no context on a on_message event

gaunt ice
slate swan
gaunt ice
#

wait

#

okk message.guild.roles

slate swan
#

would only work if the message param were name ctx

hardy yoke
slate swan
#

most popular wrapper for the discord api thats writing in python

#

but its not official*

gaunt ice
hardy yoke
#

all good 😄

gaunt ice
slate swan
final iron
#

It's just the most popular

gaunt ice
#

ohh okk

gaunt ice
#

my error is

sage otter
#

that event only takes payload

gaunt ice
#

ohh

#

TYSM

#

IT WORKS

nimble plume
slate swan
#
       newchannel = await                   
       altchannel.guild.create_text_channel(f'{channel.name}-{memberline2}', category=category)
       await newchannel.edit(sync_permissions=True)
       for member in members:
          overwrites = newchannel.overwrites_for(member)
          overwrites.send_messages = True
          await newchannel.set_permissions(member, overwrite=overwrites)```

When the code doesnt give u errors 😔
#

indentation and error handler sad

#

Its not overwritng perms as usual

slate swan
#

when i pasted

#

ah

#

discord is mean >:C

#

True

#

error handler eating it perhaps?

#

specifclly overwrites

#

its not overwriting the member to read the channel

#

and yes the member object is indeed a member object lol

#

is newchannel created?

#

yes it does get created

#

and it syncs the perms to category as intended

#

try adding a few prints here and there imo

#

i guess?

#

does it loop?
members list might be empty

#

its not empty cuz i did a ping test prior to it

#

list check*

#

interesting

#

it grabs the members from an existing VC channel and created a discord channel for the people in the vc

#

like a queuing system if that makes sense lol

#

except it doesnt queue the members...

#

which fork/version are you using?

#

nextcord ofc

#

ofc Stonks

#

well the docs says overwrites_for* wants a user object, not a member object

#

well some of it

slate swan
#

yes sir, worth a try?

#

i mean a guild member would make more sense but sure why not

#

client.fetch_user ye?

#

get_user sure

#

ah get_user

#

also use Bot instance when blobpain

slate swan
#

or u mean my decorator?

maiden fable
slate swan
#

im making this specifc line of code off a on_voice_state_update event btw

slate swan
#

do the prints reveal anything?

#

didnt try it yet

bright spade
#

what is cogs and how is it used in discord bots development

slate swan
#

lemme try the user object idea rq

slate swan
#

EXCELLENT!

#

u were right

#

just needed the user object not guild member object, thanks mate

gaunt ice
slate swan
#

neat, now to make a pr fixing that exit

#

gl lmfao

bright spade
#

k

maiden fable
bright spade
#

tnx

hardy wing
#

is there a way to not get rate limited?

slate swan
#

good code

maiden fable
slate swan
#

cooldowns and ^

hardy wing
#

what would I have to use

slate swan
#

!hosting blobpain

hardy wing
#

so I have to buy a server?

bright spade
#

how to make a bot which has interactive welcome message setup?

maiden fable
#

Yes

hardy wing
#

how much do servers usually cost

slate swan
# hardy wing so I have to buy a server?

there are a few hosts out there, let me quickly paste a tag

  1. Get a cheap VPS
    A VPS is a good way to run your bot 24/7, and they can be rented quite cheaply from various companies, some hosts include:
    https://scaleway.com/ (EU) https://digitalocean.com/ (US)
    https://linode.com/ (US/EU/Asia) https://www.hetzner.com/cloud (US/EU)
    We recommend you compare the options before choosing a provider, and look for other providers that suit you well. It is also possible to use free trials of services AWS, GCP, and Azure to run your bot for up to a year for free on a low power machine.

  2. Host locally
    If you have a RaspberryPi this can be used as a bot host quite easily, and many tutorials exist for it online. You can also host a bot on your PC if you keep it on 24/7.
    This is not recommended due to the investment involved as well as your network stability
    If you are using your PC you should consider using a VPS provider instead.

Note:
Free hosts, such as Heroku, Replit, and EpikHost, are not good hosts for your bot. Heroku and Replit are designed for websites, which is why they expose a domain for you. EpikHost is known to give away customer information and it is advised that you do not use them for this reason.

slate swan
slate swan
hardy wing
#

so that'd be on digitalocean?

slate swan
#

amazon whatstheteaspillit aws

bright spade
#

something wrong pls help

hardy wing
#

oh

#

how would you get to aws

#

like could you send a link

slate swan
#

google, first or second hit

hardy wing
#

kk

maiden fable
slate swan
#

😳 specs of the vps?

quick gust
#

i sent a link earlier

#

Lemme find

maiden fable
hardy wing
#

but could I still code it on replit or would I have to move the code somewhere else

slate swan
quick gust
quick gust
maiden fable
#

I also sent that yesterday haha

quick gust
slate swan
#

sigh site wont load Pensive_cry

maiden fable
slate swan
#

idts

quick gust
#

Yeah they do

slate swan
#

I get an ubuntu 16.04 with 1 VCPU and 1 gb ram at 6$

maiden fable
#

😂

#

U r getting 4vcpu cores

maiden fable
#

Iirc in oracle

slate swan
#

but then it's a full fledged virtual machine, perhaps it must be different for vps

slate swan
slate swan
#

but you would need to have the source in your vps/host

hardy wing
#

but the code will still work when I move it over right like how much do I have to change

#

cause still want to use it on replit rn until it's finished

slate swan
#

depends on the host

#

yup just code it locally in pycharm or something then yeet the new code to your host to run it

#

some hosts use pyproject.toml/poetry for installing reqs
some will do that for you with requirements.txt/an option to add packages

slate swan
hardy wing
#

alr alr thnx for the info

slate swan
quick gust
#

I wanna make a repo for my bot and on my host, automatically pull everything from the GitHub so I can directly commit stuff to the repo from my vsc and ez update, though I'm having a problem even making the repo lmao, it just doesn't ignore venv and the secrets file

slate swan
#

use .gitignore file

quick gust
#

i did

slate swan
#

you can specify the files and venv there ```
.env
venv/

quick gust
#

I even had the folder paths inside

#

yep I had all that

final iron
#

rin 😔

quick gust
#

im probably gonna give it another try today

#

make a new repo

slate swan
#

dont make a new repo, just clone it on your device again and it will work

#

vsc is sometimes buggy with it :V

quick gust
#

the thing is

#

i already deleted the repo and vsc still tells me to push stuff xD

gaunt ice
#

yall pro coders.....

#

i dont even understand this

pliant gulch
final iron
hardy wing
#

would I be able to use one amazon web server for both a discord bot and a website or only one thing at a time

hardy wing
supple thorn
#

Wanna hear

slate swan
#

sure

fervent shoal
#

How would I go about making an uptime command

#

I just want to see how long the bot has been up

woven ingot
#

Hi i would really appreciate some help if anyone has time. I'm pulling some data from an API and displaying it on my bot activity but the data is displaying weird have no idea how to fix it. I recently replaced the api. Not sure if maybe the way i'm round the decimals is creating the error?

#
    async def loop():
    token = open('crypto.txt', 'r').read()
    url = f"https://api-v2-mainnet.paras.id/collection-stats?collection_id={token}"

    data = requests.get(url).json()["data"]["results"]["floor_price"]
    price = str(round(float(data)*10000)/10000)
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="💎 $"+price))```
gaunt ice
final iron
final iron
#

Check if thats what the api is returning

woven ingot
#

Nop the api returns this

fervent shoal
woven ingot
#

floor_price":"110000000000000000000000000"

unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
final iron
#

Make a variable with that

fervent shoal
#

Thank u, and what

final iron
#

and what wdym

#

You got another question?

fervent shoal
#

make a variable with what

final iron
slate swan
final iron
#

Assign a variable to that

slate swan
#

name="💎 $"+str(price)

final iron
#

Then in the command subtract the current time from your variable

#

It will show uptime

woven ingot
woven ingot
woven ingot
# slate swan just use the string format of that and it will work
@tasks.loop(seconds=20)
async def loop():
    token = open('crypto.txt', 'r').read()
    url = f"https://api-v2-mainnet.paras.id/collection-stats?collection_id={token}"

    data = requests.get(url).json()["data"]["results"]["floor_price"]
    price = str(round(float(data)*10000)/10000)
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=":gem: $"+price))```
fervent shoal
slate swan
fervent shoal
#

Epic make look like code fail Xd

final iron
slate swan
#

why multiply it my 10000 and divide it again?

final iron
#
my_var = "is amazing"
fervent shoal
#

What’s after the = sign

final iron
woven ingot
final iron
#

!d round

unkempt canyonBOT
#

round(number[, ndigits])```
Return *number* rounded to *ndigits* precision after the decimal point. If *ndigits* is omitted or is `None`, it returns the nearest integer to its input.

For the built-in types supporting [`round()`](https://docs.python.org/3/library/functions.html#round "round"), values are rounded to the closest multiple of 10 to the power minus *ndigits*; if two multiples are equally close, rounding is done toward the even choice (so, for example, both `round(0.5)` and `round(-0.5)` are `0`, and `round(1.5)` is `2`). Any integer value is valid for *ndigits* (positive, zero, or negative). The return value is an integer if *ndigits* is omitted or `None`. Otherwise, the return value has the same type as *number*.

For a general Python object `number`, `round` delegates to `number.__round__`.
slate swan
slate swan
fervent shoal
#

classmethod
datetime.now(tz=None)
time.time()

woven ingot
fervent shoal
#

i know for a fact im doing this wrong, how do i fix it

woven ingot
#
@tasks.loop(seconds=20)
async def loop():
    token = open('crypto.txt', 'r').read()
    url = f"https://api-v2-mainnet.paras.id/collection-stats?collection_id={token}"

    data = requests.get(url).json()["data"]["results"]["floor_price"]
    price = str(round(float(data), 2)
    await client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=":gem: $"+price))```
slate swan
#

you want it with decimals or without decimals?

woven ingot
#

With 2 decimals

slate swan
#

!e py num_str = "1234565325632653.34532" print(round(float(num_str),3))

#

it should work then, are you sure the data that website returns is in numeric form?

woven ingot
#

Not really my old API was how do i check?

fervent shoal
#

@bot.command(name="uptime")
async def uptime(ctx: commands.Context):
await ctx.send(f"{client.uptime}")
quick google check, this should work?

final iron
#

That would just send when the bot was started

quick gust
#

they're in the same dir, just adding database.db to the gitignore will work right? no . or /?

pliant gulch
#

I would add *.db to the .gitignore to ignore all db files

#

Means you won't need to manually add it for each db file you have

quick gust
#

i see, thanks

fervent shoal
#

@bot.command(name="uptime")
async def _uptime(self,ctx):
uptime = str(datetime.timedelta(seconds=int(round(time.time()-startTime))))
await ctx.send(uptime)
i need to define startTime, any idea on how

gaunt ice
fervent shoal
#

Tbh I just don’t get the startTime part

#

I think my question is too specific for Google

final iron
#

And variable/function names should be named in the snake_case convention

#

camelCase should never be used in python

fervent shoal
#

h u h

#

ok so startTime = (something idk)

final iron
#

No

#

start_time = time code here

fervent shoal
#

why start_time instead of startTime

final iron
#

Because pep8

fervent shoal
#

and what is the time code in this case

final iron
#

!pep8

unkempt canyonBOT
#

PEP 8 is the official style guide for Python. It includes comprehensive guidelines for code formatting, variable naming, and making your code easy to read. Professional Python developers are usually required to follow the guidelines, and will often use code-linters like flake8 to verify that the code they're writing complies with the style guide.

More information:
PEP 8 document
Our PEP 8 song! :notes:

fervent shoal
#

oh I see

alpine vault
#

Is doing sys.exit() the exact same thing as raise SystemExit ? pithink

final iron
unkempt canyonBOT
#

classmethod datetime.now(tz=None)```
Return the current local date and time.

If optional argument *tz* is `None` or not specified, this is like [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today"), but, if possible, supplies more precision than can be gotten from going through a [`time.time()`](https://docs.python.org/3/library/time.html#time.time "time.time") timestamp (for example, this may be possible on platforms supplying the C `gettimeofday()` function).

If *tz* is not `None`, it must be an instance of a [`tzinfo`](https://docs.python.org/3/library/datetime.html#datetime.tzinfo "datetime.tzinfo") subclass, and the current date and time are converted to *tz*’s time zone.

This function is preferred over [`today()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.today "datetime.datetime.today") and [`utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow "datetime.datetime.utcnow").
fervent shoal
#

@bot.command(name="uptime")
async def _uptime(self,ctx):
uptime = str(datetime.timedelta(seconds=int(round(time.time()-start_time))))
await ctx.send(uptime)
start_time = classmethod; datetime.now(tz=None)
like this?

final iron
#

Bro

#

Have you tried learning python yet?

nimble plume
#

what u prefer custom help command as help command = none or in built?

fervent shoal
#

The resources I tried aren’t helping ;-;

final iron
#

The default one is ugly as hell

nimble plume
fervent shoal
#

Oh hey it’s dynos brother

nimble plume
final iron
unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

unkempt canyonBOT
#

Python/sysmodule.c lines 863 to 870

static PyObject *
sys_exit_impl(PyObject *module, PyObject *status)
/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
{
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, status);
    return NULL;
}```
slate swan
quick gust
#

yes

#

its a private repo, I wanna ignore venv because its annoying to push it every time

slate swan
#

dont you use source control?

quick gust
#

I am using source control

#

this right?

slate swan
#

left click on the files you want to add to gitignore and use "add to gitignore"

#

makes life easier

quick gust
#

right click?

slate swan
#

oh yes right click

quick gust
#

only have these

slate swan
#

from the source control

quick gust
#

ah

#

sec

#

seems the venv files arent there in the "changes" anymore

#

though I can see this green marker which I think means "new files"

slate swan
#

cool, and ill assume you use the source control for push too?

quick gust
#

yep

slate swan
nimble plume
#

!afk command comes in which category?

quick gust
#

Lib\site-packages and some of the packages inside it

nimble plume
quick gust
nimble plume
#

afk command comes in which category?

final iron
#

Utility or Misc imo

nimble plume
#

how to create these types of button

quick gust
#

they are normal buttons with custom emojis

nimble plume
#

pls provide button docs

quick gust
#

!d discord.ui.Button

unkempt canyonBOT
#

class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.

New in version 2.0.
nimble plume
#

ok

fervent shoal
#

Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 855, in invoke
await self.prepare(ctx)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 697, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/usr/local/lib/python3.7/dist-packages/discord/ext/commands/core.py", line 542, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.

class Uptime:
def init(self, bot):
self.bot = bot

@bot.command(name="uptime")
async def uptime(self, ctx):
    current_time = time.time()
    difference = int(round(current_time - start_time))
    text = str(datetime.timedelta(seconds=difference))
    await self.bot.ctx.send("Current uptime: " + text)
slate swan
fervent shoal
#

i literally do not get this, monkey brain is die

slate swan
#

you can always sync changes using this

quick gust
quick gust
quick gust
final iron
nimble plume
#

do we need to import something

#

@quick gust

fervent shoal
final iron
#

Remove it

quick gust
#

self.bot.ctx.send, ctx.send is enough

fervent shoal
#

Alr thanks so much for the help

novel bolt
nimble plume
#

button is a method?

#

no ig

fervent shoal
#

class Uptime:
def init(bot):

    @bot.command(name="uptime")
    async def uptime (ctx):
        current_time = time.time()
        difference = int(round(current_time - start_time))
        text = str(datetime.timedelta(seconds=difference))
        await bot.ctx.send("Current uptime: " + text)

says uptime isnt a command

slate swan
#

there's no button method

final iron
fervent shoal
#

The init has __ beside it and __ after it

fervent shoal
nimble plume
#

from discord import buttons?

#

cant find import for buttons on docs

fervent shoal
#

I can feel the rage of pep8 compliance officer

novel bolt
fervent shoal
#

thank so much for real

nimble plume
#

@slate swan components = #button??

novel bolt
#

make intendations correct

nimble plume
#

like this

novel bolt
fervent shoal
#

gnoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "uptime" is not found

start_time = time.time()

class Uptime:
def init(bot):
@commands.command(name="uptime")
async def uptime (self,ctx):
current_time = time.time()
difference = int(round(current_time - start_time))
text = str(datetime.timedelta(seconds=difference))
await ctx.send("Current uptime: " + text)

tfym uptime isnt found

#

same thing happened with old code

final iron
novel bolt
#

actually ur code is wrong

final iron
fervent shoal
light violet
#

@final iron bro i wanted to know that how to ban some one fast like if we use normal guild.ban then some nukers get bans after 50 bans btw it is too slow how to stop nuker at less bans bro, i was using httpx with v9 api still stopping nukers at 47 bans

final iron
light violet
#

@final iron no i wanted to ping u only, i thought that u r a proffesional

#

🥲

#

and u can help me

final iron
light violet
#

yes btw......

final iron
#

My point still stands. Don't ping random people for help

light violet
light violet
#

bruhhhh somebody help me with my bot plsss iam using https still getting nukers stop at 47 bans

#

😑 😑 pithink

nimble plume
slate swan
#

!d discord.ui.Button.callback

unkempt canyonBOT
#

await callback(interaction)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

The callback associated with this UI item.

This can be overriden by subclasses.
fading bramble
#

Does anyone know how to add your discord bot to multiple servers instead of just one? (Feel free to DM me.)

final iron
#

Just invite it?

balmy ivy
#

how could i put embeds in these

final iron
#

!d discord.Embed

unkempt canyonBOT
#

class discord.Embed(*, colour=Embed.Empty, color=Embed.Empty, title=Embed.Empty, type='rich', url=Embed.Empty, description=Embed.Empty, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

Certain properties return an `EmbedProxy`, a type that acts similar to a regular [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.9)") except using dotted access, e.g. `embed.author.icon_url`. If the attribute is invalid or empty, then a special sentinel value is returned, [`Embed.Empty`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed.Empty "discord.Embed.Empty").

For ease of use, all parameters that expect a [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") are implicitly casted to [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.9)") for you.
balmy ivy
#

ik how to use embed but it set up diff

final iron
balmy ivy
balmy ivy
quick gust
#

because u are returning so the code below it before the else doesnt reach

#

thats why its grayed out

green bluff
novel bolt
# green bluff

change guild.roles() to guild.roles and try,in line 22

green bluff
#

oh sure

boreal ravine
small igloo
#
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'coroutine' object is not iterable
@bot.command(
    aliases=["find", "google", "src"]
)
async def search(ctx,*, query):
    author = ctx.author.name
    async with ctx.typing():
        s = discord.Embed(title=f"Here are the links related to your question {author} !", description=query, colour=ctx.author.color)
        for j in search(query, num_results=10):
            s.add_field(name=j,value=":arrow_up:",inline=True)
        s.set_footer(text="Have any more questions:question: Feel free to ask again :smiley: !")
        await ctx.send(embed=s)

:bruh: