#discord-bots

1 messages · Page 1136 of 1

slate swan
#

```py
Text

slate swan
viral dock
#

oooh tnx

slate swan
#

😋

viral dock
#

So then the code is like this?:

#botcommand

#command Hello
@bot.command()
async def test(ctx):
  await ctx.send("hello")

  if message.content.startswith("*Hello"):
    await message.channel.send('Hello!')
shrewd apex
#

?

#

whats this?

sage otter
#

The cooldown decorators are meant to be applied to commands not buttons. You have to do your own implementation.

viral dock
slate swan
rustic onyx
#

Is RequestsWebhookAdapter this a thing on discord.py

#

Its not in the discord module as I see but idk they use it there

rustic onyx
#

meaning its not now?

paper sluice
#

nope

rustic onyx
#

what would be the alternative to it? wanna avoid creating a bot

#

🤔

#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks") and [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
paper sluice
clever socket
#

indent the last else

#

it's outside of the loop right now

clever socket
#

Yes it is?

paper sluice
#
for ...:
    # inside for loop
# outside for loop
clever socket
#

well, it's outside of the loop, right now, it should be:

for index, member in enumerate(role.members):
    if foRole in member.roles:
        fo = f"{member.mention} `{member}`"
    elif hcRole in member.roles:
        hc = f"{member.mention} `{member}`"
    elif gmRole in member.roles:
        gm = f"{member.mention} `{member}`"
        inline=True    
    else:
        memberList.append(f"`{member}`")
#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

rustic onyx
#

a webhook basically haha

paper sluice
#

discord.Webhook should be good enough then

rustic onyx
#

!d discord.Webhook

unkempt canyonBOT
#

class discord.Webhook```
Represents an asynchronous Discord webhook.

Webhooks are a form to send messages to channels in Discord without a bot user or authentication.

There are two main ways to use Webhooks. The first is through the ones received by the library such as [`Guild.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.webhooks "discord.Guild.webhooks"), [`TextChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.TextChannel.webhooks "discord.TextChannel.webhooks") and [`VoiceChannel.webhooks()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.webhooks "discord.VoiceChannel.webhooks"). The ones received by the library will automatically be bound using the library’s internal HTTP session.

The second form involves creating a webhook object manually using the [`from_url()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.from_url "discord.Webhook.from_url") or [`partial()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Webhook.partial "discord.Webhook.partial") classmethods.

For example, creating a webhook from a URL and using [aiohttp](https://docs.aiohttp.org/en/stable/index.html "(in aiohttp v3.8)"):
slate swan
#

wait hol up how do u have that layout i just have the plain white and latest which one is that/

minor oriole
#

I want to make an asynchronous Python API Wrapper like Pycord/Nextcord/Discord.py etc as a side project

Can someone help me out on starting out and how to go abt understanding their masive number of github file names?

slate swan
#

guys i need a bot to spam someones dms

#

wont help

#

can somene helppp 🥺

#

please i gotta troll my friend 🥺

#

help pls

slate swan
slate swan
#

multiple people

#

please

slate swan
# slate swan i want a bot to do it can u help 😭
from discord.ext import commands, tasks
import discord

bot = commands.Bot(...)

@tasks.loop(...)
async def uwu():
  await (bot.get_user(_id) or await bot.fetch_user(_id)).send(...)
  
uwu.start()
bot.run(...)
#

how to actuarraly use it in the bot and set commands? i know we have to go to the develepor page and stuff im there and i created a new bot

#

@slate swan

slate swan
slate swan
slate swan
slate swan
#

sorry i don't help in making spam bots.

slate swan
slate swan
regal pulsar
# slate swan guys i need a bot to spam someones dms
from discord.ext import commands
import discord

bot = commands.Bot(test_guilds=[your priv server])

@bot.slash_command()
async def dm(id: int, amt: int, *, msg: str):
    user = bot.get_user(id) or await bot.fetch_user(id)
    for _ in range(amt):
        await user.send(msg)

bot.run(TOKEN)
regal pulsar
#

doesnt really matter that much

slate swan
#

oh ok.

#

sarthak I wanna fork you and keep you with me forever 😔

sage otter
minor oriole
#

Uh

slate swan
#

i think interaction_check coro can be utilised for that

minor oriole
#

Can someone suggest me on how to go abt making a Python Discord Library?

shrewd apex
# slate swan 😭
import discord
from discord.ext import commands, tasks

bot = commands.Bot(command_prefix ='.', intent=discord.Intent.all())

@tasks.loop(seconds=1)
async def spam():
    spamming =['enter ids here']
     for i in spamming:
         user= bot.get_user(i) or await bot.fetch_user(i)
         user.send('spam')

@bot.event
async def on_ready():
     spam.start()

bot.run('Token')
sage otter
#

Cooldowns are separate from checks

slate swan
#

im not talking about the decorator fyi

sage otter
#

Idk then.

slate swan
#

!d discord.ui.View.interaction_check this is triggered whenever someone interact's with this view's items

unkempt canyonBOT
#

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

A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.

This is useful to override if, for example, you want to ensure that the interaction author is a given user.

The default implementation of this returns `True`.

Note

If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
slate swan
slate swan
#

found this guy who asked for a discord bot when i made it and hardworked he said no f u n word and then started being racist and swearing 😭 people wasting our time

#

i dont know why people like this exist

#
class MyView(discord.ui.View):
  cooldown = False
  
  async def interaction_check(self)-> bool:
      if self.cooldown: return False
      return True

  @discord.ui.button(**kwargs)
  async def callback(self, inter, button):
    # do your stuff
    self.cooldown = True
    await asyncio.sleep(seconds to wait for)
    self.cooldown = False
``` not the best way, but it works.
slate swan
sage otter
#

that’s definitely not the best way to do it

#

Plus they want a dynamic cooldown

#

Not a global cooldown

slate swan
warped mirage
#

how do u make a bot show a ping role in a embed

#

i tried <@ID>

slate swan
sage otter
#

Yea, I was just adding on to what you said.

shrewd apex
slate swan
slate swan
slate swan
warped mirage
#

ok

shrewd apex
slate swan
shrewd apex
#

next level😳

slate swan
slate swan
slate swan
unkempt canyonBOT
#

Cooldowns in discord.py

Cooldowns can be used in discord.py to rate-limit. In this example, we're using it in an on_message.

from discord.ext import commands

message_cooldown = commands.CooldownMapping.from_cooldown(1.0, 60.0, commands.BucketType.user)

@bot.event
async def on_message(message):
    bucket = message_cooldown.get_bucket(message)
    retry_after = bucket.update_rate_limit()
    if retry_after:
        await message.channel.send(f"Slow down! Try again in {retry_after} seconds.")
    else:
        await message.channel.send("Not ratelimited!")

from_cooldown takes the amount of update_rate_limit()s needed to trigger the cooldown, the time in which the cooldown is triggered, and a BucketType.

warped mirage
warped mirage
slate swan
warped mirage
#

no not mention

#

it doesnt show the role tho

slate swan
#

did you enter the correct ID?

shrewd apex
warped mirage
#

field

shrewd apex
#

name or value

slate swan
#

you cant do that in field names

warped mirage
slate swan
#

you cant mention in names or title

shrewd apex
warped mirage
#

what do i do then?

slate swan
#

use the value

#

just use the name if you want to do display the role name in the field name

warped mirage
#

can i change the <@userid> in name then? so that it works

slate swan
#

so many name

warped mirage
#

oof

shrewd apex
#

make the name empty space

#

and design ur embed format

warped mirage
#

ok

shrewd apex
#

in value

slate swan
#

field names and Embed title only support simple text and hyperlinking for the title

#

and emojis

shrewd apex
#
embed.add_field(name='\u200b', value='<role>\nstuff')
shrewd apex
slate swan
#

the emoji thing has been added recently so yeah

shrewd apex
#

it was seriously bad b4

#

they should allow in footer as well

slate swan
#

how do you get member's avatar url in the new dpy

#

before it was member.avatar_url but idk now

shrewd apex
#

display_avatar

#

or avatar.url

slate swan
#

avatar.url, alright thanks!

slate swan
slate swan
#

oh

austere vale
#
  @commands.Cog.listener()
  async def on_member_leave(self,member:nextcord.Member):
    embed=nextcord.Embed(color=0xfd9fa1, description= f'{member.mention}{member.name}{member.discriminator}', title='Member Left')
    if member.avatar is None:
        embed.set_thumbnail(url=member.default_avatar,
        icon_url=f'{member.default_avatar}')
        embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
    else:
        embed.set_thumbnail(url=member.avatar.url)
        embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
        embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
    embed.timestamp=datetime.datetime.utcnow()
    await self.bot.get_channel(933978399280599080).send(embed=embed)

this is my action log message for members leaving, but it wont send an embed or an error when someone leaves. does anyone know why?

slate swan
#

on_member_remove @austere vale

austere vale
#

ooooo so not leave

#

ty

slate swan
#

yep,"remove" makes more sense because this event is also fired when a member is Kicked from the guild.

austere vale
#

oh how come ?

#

should the icon_url thing be removed entirely

slate swan
#

yes

#

and default_avatar returns an Asset object not a url

austere vale
#

ooo oki

#

thank you

unkempt canyonBOT
#

discord/asset.py lines 328 to 329

def __str__(self) -> str:
    return self._url```
austere vale
#

yea im putting it in an f string

slate swan
slate swan
slate swan
unkempt canyonBOT
#

discord/embeds.py lines 398 to 401

else:
    self._image = {
        'url': str(url),
    }```
slate swan
slate swan
#

ofc, ew 😂

#
@client.command()
@commands.has_permissions(mute_members=True, administrator=True)
async def timeout(ctx: commands.Context, member: discord.Member, until: int):
    handshake = await timeout_user(user_id=member.id, guild_id=ctx.guild.id, until=until)
    if handshake:
         return await ctx.send(f"Successfully timed out {member.display_name} for {until} minutes.")
    await ctx.send("**ERROR**")
    await ctx.send("Something went wrong")
    await ctx.send("Attempting to find the issue...")
    time.sleep(5)
    await ctx.send("Issue Found!")
    await ctx.send("Incorrect Usage! Usage: t!timeout @person#0000 1h/hour")```
#

thats how every library does it anyways, they are converting it for the payload to send on discord

#

it works but u need mute_members AND administrator

#

mute_members is not a permission

slate swan
#

I saw it in the discord role area

#

where u give perms to a role

#

discord.py 1.7.3 didn't implement that, that has been added recently
and its Manage Members iirc

#

*Timeout Members.

#

moderate*

slate swan
#

!d discord.Permissions.mute_members

unkempt canyonBOT
slate swan
#

for voice channels

slate swan
slate swan
slate swan
#

no

#

😔 if i were referring to the dpy perm i would have said timeout_member

#

~~ idky its not in UPPERCASE but ok~~ they are all @quaint stream_values

#

nice

paper sluice
#

people with unfortunate names 😔

slate swan
#

i mean yeah

slate swan
#

they didnt get a ping

slate swan
#

oh sorry

slate swan
#
@client.command(aliases=['banuser'])
@commands.has_permissions(ban_members=True)
async def ban(ctx, member : discord.Member, *, reason= "No reason was provided"):
    member_name, member_disc = member.split('#')
    
    await ctx.send(":white_check_mark:", member_name + member_disc + "Banned them from the server")
    await member.ban(reason=reason)```
#

it doesnt do anything, no errors, no nothing

paper sluice
#
    await ctx.send(":white_check_mark:", member_name + member_disc + "Banned them from the server")

that works for print not ctx.send, use f-strings

    await ctx.send(f":white_check_mark: {member_name}{member_disc}Banned them from the server")
slate swan
paper sluice
#

they didnt have the # so didnt put it

slate swan
#

for member in guild.members:
AttributeError: 'NoneType' object has no attribute 'members'

#

help

slate swan
quaint epoch
#

because in this context guild is None

slate swan
#

in a task

quaint epoch
#

it might be an issue with your scope

#

i gotta see it first though

slate swan
#
tinv = 0

@tasks.loop(seconds=50)
async def inv():
  global tinv
  guild = bot.get_guild(921366728016011324)
  for member in guild.members:
      print(member)
      for i in await guild.invites():
          print(i)
          if i.inviter == member:
            tinv += i.uses
          else:
            continue
slate swan
quaint epoch
unkempt canyonBOT
slate swan
#

what

quaint epoch
#

iirc it can return None if the guild is not in the bots cache

slate swan
quaint epoch
#

i haven't worked with dpy for a few months now

slate swan
#

i dont even use dpy anime_glasses

left idol
#

how many people can i role at one time?

quaint epoch
slate swan
#

hikari ftw

quaint epoch
#

you mean how many people you can add roles to at once?

left idol
#

i tried adding a role to 13 people

#

but it stopped at 11

quaint epoch
#

you can't fix those

left idol
#

ah ok, should i add a wait time

quaint epoch
#

yup

#

sarth - what was the limit of requests/minute for adding roles to members with the api?

slate swan
#

its dynamic, there's no fixed ratelimit for that
but yes you should be able to add roles to 15 people in 2-3 seconds

left idol
#
@bot.command()
@commands.has_role("Phase 3")
async def addrole(ctx, role: discord.Role, members: commands.Greedy[discord.Member]):
#async def addrole(ctx, role: discord.Role, *members: discord.Member:
    for member in members:
        if role in member.roles:
            await ctx.send(f"<@{member.id}> already in {role}")
        else:
            await member.add_roles(role)
            await ctx.send(f"{role} added to <@{member.id}>")
slate swan
#

just asyncio.sleep for 0.2 - 0.5 seconds before adding a role

#
# Запуск бота
    @commands.Cog.listener()
    async def on_ready(self):

        cursor.execute("""CREATE TABLE IF NOT EXISTS users(
            id INT,
            name TEXT,

            gems BIGINT,
            iron BIGINT,
            wood BIGINT,
            organic BIGINT,
            detals BIGINT,
            batteries BIGINT,
            fragments BIGINT,

            work TEXT,
            job_title TEXT,
            experience INT,
            Tool TEXT,

            user_level_chat BIGINT,
            user_xp_chat BIGINT
            )""")

        cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
            id INT,
            name TEXT,

            work_1 INT,
            work_2 INT
            )""")

        for guild in self.client.guilds:
            for member in guild.members:
                if cursor.execute(f"SELECT id FROM users WHERE id = {member.id}").fetchone() is None:
                    cursor.execute("INSERT INTO  users VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", (f'{member.id}', f'{member}', 0, 0, 0, 0, 0, 0, 0, 'None', 'Безработный', 0, 'Руки', 1, 0))
                    cursor.execute("INSERT INTO  cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', 1, 1))
                else:
                    pass
                conn.commit()
        print("READY!")

Dear prompt why only 1 table?

#

which table got created?

#

users

#

cooldown is not created for some reason

#

you use CREATE TABLE IF NOT EXISTS, maybe the table is already there?

#
    @commands.command(name = "3")
    async def comand_col(self, ctx):
        data = cursor.execute(f"SELECT work_1 From cooldown WHERE id = {ctx.author.id}").fetchone()[0]
        await ctx.send(f"{data}")

I previously deleted the database. and made a test command which gave an error. also opening the database itself did not find the second table

thick basin
#

how many times can I change the role colour? I mean do I get ratelimited if I change it per minute

slender mesa
#

how would i make a welcome message embed? i have the json for the embed but idk how to put it into the code

slate swan
#

!d discord.Embed.from_dict

unkempt canyonBOT
#

classmethod from_dict(data)```
Converts a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") to a [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") provided it is in the format that Discord expects it to be in.

You can find out about this format in the [official Discord documentation](https://discord.com/developers/docs/resources/channel#embed-object).
slate swan
slate swan
#

@slate swanOh I got it. If a separate command to create tables that works!!! thanks for the help!!!

slate swan
#

also that isn't an embed?

#

he wanted to make an embed with a dict and im pretty sure he just wanted to know which method he can use which sarth gave it to him

slate swan
#

Nice Itsuki Nakano pfp on your github

slate swan
#

well,
I installed discord -> npm install discord.js
I installed requests -> python -m pip install requests
I installed discord.ext -> pip install discord.ext.context

#

and colorama nad httpx i dont remember

#

Why are you installing JS discord?

#

httpx -> pip install httpx

slate swan
#

my friend said that i have to have discord.js to have the import discord

#

resolved

#

what language do you want to code in?

#

python ofc

#

then don't install discord.js

#

oh

#

well, hehe

#

okey thanks

#

this video teaches you how to install libraries

slate swan
slate swan
slate swan
slate swan
# slate swan https://youtu.be/ThU13tikHQw

"cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwli
nk/?LinkID=135170."

idk, i downloaded the venv like he do but at the end i got errors but i get the venv?

#

is it something i should skip or is this a serious issue?

#

are you on a virtual machine or something?

#

ye, my pc

slate swan
#

ye

#

physical

#

I've never gotten that error before I've got no clue

#

could someone here help me? pls!!!

solemn flame
#

is there a limitation on creating a modal from a response to a modal

slate swan
cloud dawn
cloud dawn
#

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

slate swan
#

how do I install "git"?

cloud dawn
slate swan
#

got error

torn sail
slate swan
#

i did it

#

but i get error

torn sail
#

and find the download area

slate swan
#

and download it?

torn sail
#

yes

slate swan
#

okok brb

slate swan
#

witch one?

#

the first one?

torn sail
slate swan
#

okok

slate swan
#

now what

torn sail
slate swan
#

i got the same error in powershell

#

...

vague cedar
#

So I'm trying to make a discord bot that when I write $doit it sends all the files in the image folder but I would like it to do it one by one
So basically make a for loop and send the images

import discord
import os

client = discord.Client()

@client.event
async def on_ready():
  print('Logged in as')
  print(client.user.name)
  print(client.user.id)
  print('------')


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$doit'):
        await message.channel.send(file=discord.File("./images/*"))

client.run("OT*****************************************")
torn sail
torn sail
slate swan
vague cedar
#

but now how do I do the for loop

torn sail
flat solstice
#

So I'm trying to declare my clients owner_ids like thispy client.owner_ids = owner_id for owner_id in client.config.owners.strip().split(",") if client.config.owners is not None else []but I'm getting a owner_id is not defined error, can someone help me figure out why?

torn sail
slate swan
#

fakk...

torn sail
#

maybe someone else will come along and know

slate swan
#

i hope so...

vague cedar
torn sail
#

sounds nice

vague cedar
#

thank you so much 🙂

torn sail
#

try just making the if statement multiple lines

slate swan
#

Ping me if someone know this problem^^

#

NOW @torn sail

#

I think

torn sail
#

?

slate swan
torn sail
#

oh

#

hmm it didnt work from command promt tho

slate swan
#

mhm

#

so now what?

torn sail
#

now you should be able to import it

slate swan
#

omg now its resolved

torn sail
#

import discord

slate swan
#

Omg im so glad

#

:D

#

thanks for help! I will return if I got new issues :D

torn sail
#

👍

flat solstice
slate swan
#

should i install all these?

#

@torn sail

torn sail
#

im pretty sure the rest are built in

slate swan
#

httpx is installed

#

req too

torn sail
#

then try and and see if it works

slate swan
vague cedar
#

@torn sail I have a weird error

unkempt canyonBOT
#

Hey @vague cedar!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

vague cedar
slate swan
#

@torn sail

torn sail
#

commands.Bot

slate swan
torn sail
#

not discord.Bot

slate swan
#

i cant find it in my file

#

lol

#

oh nvm, im so tired

cursive barn
#

@vague cedarthere is a pin in this channel to help you resolve that. it was a massive bug for a while.

torn sail
slate swan
#

but get more errors

cursive barn
slate swan
#

def get_cookies(s, url):
try:
cookieinfo = s.get(url, timeout=5).cookies
dcf = str(cookieinfo).split('__dcfduid=')[1].split(' ')[0]
sdc = str(cookieinfo).split('__sdcfduid=')[1].split(' ')[0]
return dcf, sdc
except:
return "", ""

slender mesa
#

im trying to make it so i get a msg in the py file when someone joins the server the bot is in but it doesnt seem to work

slate swan
#
@client.command()
async def devs(ctx, author):
    if author.id == "625025751413948436":
        await ctx.send("oh, hello there master")

    embed=discord.Embed(title="Developers", description="Timmy Developers", color=0x0400ff)
    embed.add_field(name="Developers", value="Clicks#8882", inline=True)
    embed.add_field(name="Lead Developers", value="Clicks#8882", inline=True)
    embed.add_field(name="Helpers", value="All the people over at the Pythone discord, they are amazing and very helpful. Join their discord if you ever need any help. join at ___", inline=True)
    embed.set_footer(text="Want to be a developer? Join the development discord server and ask! t!discord • Updated on 2022/07/04")
    await ctx.send(embed=embed)```
#

no output

#

nothing. no error message, no embed sent, no message sent

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 Members, Message Content, and Presences. These are needed for features such as on_member events, to get access to message content, 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.

torn sail
slate swan
#

it just what i got

slender mesa
#

that still didnt seem to work :(

torn sail
#

did u enable it in the dev portal

slender mesa
#

yeah

slate swan
#
@client.command()
async def devs(ctx, author):
    if author.id == "625025751413948436":
        await ctx.send("oh, hello there master")

    embed=discord.Embed(title="Developers", description="Timmy Developers", color=0x0400ff)
    embed.add_field(name="Developers", value="Clicks#8882", inline=True)
    embed.add_field(name="Lead Developers", value="Clicks#8882", inline=True)
    embed.add_field(name="Helpers", value="All the people over at the Pythone discord, they are amazing and very helpful. Join their discord if you ever need any help. join at ___", inline=True)
    embed.set_footer(text="Want to be a developer? Join the development discord server and ask! t!discord • Updated on 2022/07/04")
    await ctx.send(embed=embed)```
upper belfry
#

any1 knows what it means when writing (embed=embed) to create an embed

#

I know what is its use

#

but idk how it works

desert heart
#

Arguments can be passed based on their position or using a keyword.

#

In this case, send() has defined the embed argument to be keyword-only. This means it cannot be passed just based on its position.

#

Hence, embed= is needed in front (embed is the keyword)

slate swan
#

!args-kwargs

unkempt canyonBOT
#

*args and **kwargs

These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.

Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.

Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.

Use cases
Decorators (see !tags decorators)
Inheritance (overriding methods)
Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
Flexibility (writing functions that behave like dict() or print())

See !tags positional-keyword for information about positional and keyword arguments

cursive barn
#

that usage doesn't really make much sense when you consider what the command does.
I would suggest removing the function argument author and then to check whether or not your command was run by you, use ctx.author

slate swan
slate swan
cloud dawn
slate swan
#

for?

cloud dawn
#

No I'm asking if you have one in your code.

slate swan
#

no

#

removed all of them

cloud dawn
slate swan
cloud dawn
slate swan
#

mk

cloud dawn
#

Since you are working in a function return is used so you can stop the function from going further.

wicked atlas
#

I got bored so I did it

shrewd apex
#

revival of Tetris

wicked atlas
#

Had to stay within 5 message edits / 2 seconds though

slate swan
slate swan
wicked atlas
#

yeah

shrewd apex
#

still nice for 4-5 players at a time in channel

slate swan
#

because making games concurrently would easily get ratelimited

pliant gulch
#

ANSI finally utilised well

shrewd apex
#

it's alright to set a max concurrency for the command

wicked atlas
#

the ANSI looks great unless you're on mobile

slate swan
shrewd apex
#

indeed

slate swan
#

ansi on phone is cursed

slate swan
wicked atlas
slate swan
#

if you have the game on 2 guilds your bot would easily get ratelimited

shrewd apex
#

;-;

slate swan
shrewd apex
#

my eyes

slate swan
#

mobile client is just horrible smh

wicked atlas
#

truly

slate swan
#

what else can you expect from a mobile phone

#

more

shrewd apex
#

better rendering

wicked atlas
#

more

#

I wonder, since I'm using the interaction token to edit the message, is the ratelimit per-interaction?

#

Can't possibly be

pliant gulch
#

The ratelimit bucket will be per token

#

As it's using a webhook really, which is one of the major params when determining buckets

slate swan
# slate swan more

they couldn't get more widely used langauges like cpp to render on phone, ansi ...

#

I've seen only python, javascript & rust codeblocks on phone yet

wicked atlas
#

I have seen codeblocks, but no code formatting on phone 💀

slate swan
#

not that im aware of, maybe they would release a "buy nitro to use x language codeblocks" on phone

slate swan
slender mesa
#

how do i fix this

slate swan
#

await was used outside accoroutine, move it inside an async function

full lily
#

Why is it in the global scope

#

Put it into a function

#

When did you want it to send, that's what you should ask yourself

wicked atlas
#

So i can have as many of these going as i want supposedly

pliant gulch
slate swan
#

you won't find much difference even if it did 🗿 they all appear same

slate swan
wicked atlas
#

so basically per user

slate swan
#

you can interact with the button without caring about ratelimits?

wicked atlas
#

I mean, the buttons do have their own cooldown

slate swan
#

dont buttons have ratelimitslemon_raised_eyebrow

#

i'm pretty sure there should be some ratelimit for editing the message tho cause they are literally just webhook messages

wicked atlas
#

you can't click them too fast, but the message edit ratelimits are per interaction, and I just use the slash command's interaction token

cloud dawn
static topaz
#

how would one go about formatting an output from a sqlite3 db? This is what I see currently

slate swan
slate swan
slate swan
static topaz
#

just cleaning the text up so it looks nicer

slate swan
#

a dataclass or a parser function would be good

slate swan
cloud dawn
static topaz
#

I'm at a very basic level here :p like, learning to crawl basic level haha

wicked atlas
slate swan
#

!join read this

unkempt canyonBOT
#

Joining Iterables

If you want to display a list (or some other iterable), you can write:

colors = ['red', 'green', 'blue', 'yellow']
output = ""
separator = ", "
for color in colors:
    output += color + separator
print(output)
# Prints 'red, green, blue, yellow, '

However, the separator is still added to the last element, and it is relatively slow.

A better solution is to use str.join.

colors = ['red', 'green', 'blue', 'yellow']
separator = ", "
print(separator.join(colors))
# Prints 'red, green, blue, yellow'

An important thing to note is that you can only str.join strings. For a list of ints,
you must convert each element to a string before joining.

integers = [1, 3, 6, 10, 15]
print(", ".join(str(e) for e in integers))
# Prints '1, 3, 6, 10, 15'
cloud dawn
#

I think it's highly unlikely you won't get rate limited when running that concurrently. That is if you want your bot not to break several ToS rules.

wicked atlas
#

Haven't gotten ratelimited yet, so

cloud dawn
#

On how many instances of the game?

static topaz
# slate swan !join read this

so currently the code I have is

    with conn:
        cur.execute(f"SELECT seriesName from sonarr WHERE discord_ID=?", [id])
        return cur.fetchall()

def results(ctx):
        discord_user = get_create_user(ctx.author)
        return get_user_subscriptions(ctx, discord_user[0])```
wicked atlas
static topaz
#

when I tried to add (separator.join( before the (ctx etc in the last line, it threw an error in vsc saying the first ( wasn't closed?

wicked atlas
#

I'm gonna test it on a few more at a time, see what I get

slate swan
#

!e

print(" ".join(map(str, sum([(1, 2) , (3, 4)], ()))))
unkempt canyonBOT
#

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

1 2 3 4
slate swan
#

!e ```py
a = [("apple",), ("banana",)]
print("\n".join(i[0] for i in a))

unkempt canyonBOT
#

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

001 | apple
002 | banana
slate swan
#

better ;-;

static topaz
#

yeah that second option would work nicely

slate swan
#
  • readable
cloud dawn
unkempt canyonBOT
#

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

1 2 3 4
slate swan
#

here we go

static topaz
#

so how does that work with a return function?

slate swan
#

we gave him ideas ig

slate swan
slate swan
#

another sidenote: since you're in an async environment, aiosqlite would be a better choice.

#

!pip aiosqlite basically sqlite3 with async/await syntax

unkempt canyonBOT
static topaz
wicked atlas
hardy yoke
slate swan
static topaz
#

ah k will have a look, cheers

cloud dawn
wicked atlas
hollow zealot
#

is hikari good?

slate swan
#

i guess it will

austere vale
#
  @commands.Cog.listener()
  async def on_member_ban(self,member:nextcord.Member):
    embed=nextcord.Embed(color=0xfd9fa1, description= f'{member.mention}{member.name}{member.discriminator}', title='Member Banned')
    if member.avatar is None:
        embed.set_thumbnail(url=f'{member.default_avatar}')
        embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
    else:
        embed.set_thumbnail(url=f'{member.avatar.url}')
        embed.set_author(name=f'{member.name}', icon_url=f'{member.avatar.url}')
        embed.set_footer(text=f'{member.guild}', icon_url=f'{member.guild.icon.url}')
    embed.timestamp=datetime.datetime.utcnow()
    await 

does anyone know how to fix this?

delicate moat
#

oh wait im dumb its an event mb

austere vale
#

oh its just an audit log embed for banning

#

and when i banned someone it sent the error and didnt send the embed

hardy yoke
slate swan
#

!d discord.on_member_ban

unkempt canyonBOT
#

discord.on_member_ban(guild, user)```
Called when user gets banned from a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").

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

dpy ew gives me a stroke

#

the naming conventions

tacit storm
# slate swan better than dpy and its forks.

thats majorly subjective imo. they would have to use both to see which ones better because whats better is what they think of the library

neither are bad or anything but what makes it good is how you like the library

hardy yoke
#

the library that I use is the best and all the others are the worst

tacit storm
#

oh hell yeah i can get around thet statement chad

slate swan
#

I think you guys haven't seen the paragraphs sarth has posted on why hikari is better than dpy.

#

the 3 statements arent written by him ofc, but iirc this is one of the paragraphs

tacit storm
#

i haven’t because im barely ever active in this server and quite frankly, i dont care that they’ve written paragraphs on it lollll

if i like a library and it’s my perference, then it’s my preference and noting will change that. so someone writing paragraphs on a subjective subject is stupid

#

(which is a bit ironic since thatd what im doing)

slate swan
#

i think were talking about lib abstractions and not personal preference

#

i think he aimed the statement on performance and and implementation of the dpy project

#

some people like the commands structure ofc but some people implemented the same thing but better, i think thats his point, the impl of some features. it would be cool to see a full dpy rewrite and see all the old codebase be replaced with a new one

slate swan
shrewd apex
#

what is the function to get a list of cog objects

slate swan
#

!d discord.ext.commands.Bot.cogs

unkempt canyonBOT
slate swan
#

this only returns the names ig

shrewd apex
#

yes

#

i used get cog to fetch them

#

then using it

slate swan
#

create a list and a task and make it update a botvar every x time if you want it to or just do stuff in the setup_hook

shrewd apex
#

it dosent return a list

#

it returns a dict

#

which maps name and object

slate swan
#

lol

shrewd apex
#

i just saw

#

rip

slate swan
#

iirc its a dict that isnt mutable

#

so it doesnt have __setattr__

shrewd apex
#

i only need the keys and values tho

slate swan
#

lol

shrewd apex
#

now time to grind and write help command help descriptions🥲

slate swan
#
@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, MissingPermissions):        
        embed=discord.Embed(description=f"🚫・{member.metion} You have no permissions to use this command"color=0xfe4343)
        await ctx.send(embed=embed)
    else:
        raise error
    embed=discord.Embed(description="🚫・{member.metion} You have no permissions to use this command"color=0xfe4343)
    ^
IndentationError: expected an indented block after 'if' statement on line 53

Does someone know what am i doing on this command?

slate swan
shrewd apex
slate swan
robust fulcrum
#

I filled the form for api acces but till now they have not sent me the api key on mail

spring flax
#

can someone remind me how to make this function be called whilst the bot is running```py
class Timeouts(commands.Cog):
def init(self, bot):
self.bot =

async def get_timeouts(self):
    ...
warm tulip
#

hello guys how i can make a give role cmd !role @idk @role

paper sluice
unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have the [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") permission to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
spring flax
#

when the cache is filled

slate swan
#

do you load the cog when the bot starts running or before that?

warm tulip
slate swan
#

!d discord.ext.commands.Cog.cog_load use this with Bot.wait_until_ready

unkempt canyonBOT
#

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

A special method that is called when the cog gets loaded.

Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.

New in version 2.0.
spring flax
#

does this work?

paper sluice
slate swan
robust fulcrum
#

How we can make a running text comamnd? Like it's on the screens
Like >runningtext <text here>
Which makes the text running from left to right in the embed

paper sluice
#

make a gif which has the text running across it, then send it in the embed?

robust fulcrum
#

Not like it's on the screens

#

Not image

#

Like it edits the messega every 1 seconds

#

Like
hello world
D hello worl
ld hello wor
old hello wo

paper sluice
#

you will be rate limited

robust fulcrum
#

Hmmm

robust fulcrum
#

Replit makes rate limited

robust fulcrum
robust fulcrum
paper sluice
robust fulcrum
slate swan
#

image manipulation with dpy is a mess 😔

robust fulcrum
#

Like
hello
o hell
lo hel
llo he
ello h
hello

paper sluice
#

make multiple images with the different texts, then combine them into one gif

robust fulcrum
#

No not images

robust fulcrum
slate swan
#

every gif is a pack of frames aka images

paper sluice
#

if you like getting ratelimited, then message.edit(new-message)

robust fulcrum
#

Oof

#

I not mean this

robust fulcrum
paper sluice
#

right, where was edit_message pithink ?

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

ah yes

slate swan
#
class MyBotEvent(commands.Bot):
    def __init__(self):
        super().__init__(
            command_prefix=ConfigurationData['command_prefix'],
            intents = discord.Intents.all(),
            application_id=ConfigurationData['ConfigurationID'])
        self.individual_cogs_list = []

    async def setup_hook(self):
        for command_and_events_folder in os.listdir("./cogs"):
        # Now we have a object for each folder
            for individual_cog in os.listdir("./cogs/"+command_and_events_folder):

                if individual_cog.endswith('.py'):
                    individual_cog = f"cogs.{command_and_events_folder}.{individual_cog}"
                    self.individual_cogs_list.append(individual_cog[:-3])

        for cog_to_load in individual_cogs_list:
            try:
                await self.load_extension(cog_to_load)
                print(f"[SYSTEM] {cog_to_load} Loaded")

            except Exception as exception:
                print(f"[SYSTEM] {cog_to_load}: {exception}")

        await bot.tree.sync(guild=discord.Object(id=int(ConfigurationData['ServerGuildID'])))

I read 2.0 migration changes, and I updated my bot. But, it still won't seem to work. Can anyone help

shrewd apex
robust fulcrum
#

Hmm

shrewd apex
slate swan
shrewd apex
slate swan
shrewd apex
#

it gets unnecessarily complicated with images

robust fulcrum
slate swan
slate swan
#

in what way

slate swan
#

seems pretty neat, but I may be wrong. Lmk how to clean

#

redundant

#

ouu tryina reduce that, where can I make changes

shrewd apex
#

!e

string = 'hello world'
lst = [string[i:]+string[:i] for i in range(len(string))]
print('\n'.join(lst))
slate swan
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your eval job has completed with return code 0.

001 | hello world
002 | ello worldh
003 | llo worldhe
004 | lo worldhel
005 | o worldhell
006 |  worldhello
007 | worldhello 
008 | orldhello w
009 | rldhello wo
010 | ldhello wor
011 | dhello worl
slate swan
#

maybe combine the 2 statements

paper sluice
slate swan
#

regardless of redundancy rn. Is there anything WRONG

slate swan
slate swan
paper sluice
slate swan
#

no errors, it doesn't say anything

paper sluice
slate swan
slate swan
robust fulcrum
paper sluice
slate swan
#

Underneath that segment of code it says

BotEvent = MyBotEvent()
BotEvent.remove_command('help')

# Load global varibles to use in the cog files
BotEvent.ConfigurationData = ConfigurationData

# Edit data tiers in the bot
if not BotEvent.ConfigurationData["BotTier"] == "custom":
    BotEvent.ConfigurationData["BotAccessModules"] = TierInfoData[BotEvent.ConfigurationData["BotTier"]]


# Create Cogs List to refer to
BotEvent.run(ConfigurationData['bot_token'])
shrewd apex
#
for i in os.listdir('cogs'):
    if '.py' in i:
        await bot.load_extension(f'cogs.{i.replace(".py", "")'})
slate swan
#

ew

slate swan
robust fulcrum
#

My school tommorow and my 1 holidays work not done 😨

shrewd apex
#

yeah either

slate swan
#

cool thank you!

shrewd apex
#

i can do it in one line as Ashley said

slate swan
#
[await self.load_extension(f"cogs.{file[:-3]}") for file in os.listdir("cogs/") if file.endswith(".py") and not file.startswith("_")]

easy peasy

shrewd apex
#

but code needs to be readable

slate swan
#

uhhh W

#

nice nice thank you! @slate swan

#

lmao welcome

shrewd apex
#

or sarth & black gonna kill me

slate swan
#

black? racist asher

#

but why isn't it even loading the cog?

shrewd apex
#

smh

#

!pypi black

unkempt canyonBOT
slate swan
#

it doesn't even error out

slate swan
#

sad

#

it just sits there

#

😦

#

any issues?

shrewd apex
#

add a print statement

slate swan
#

I'm tryina use buttons and menus but they are only available for V2 rn IG. So I gotta redo my bot

shrewd apex
#

to check

slate swan
shrewd apex
slate swan
#

2.0

#

the github release

shrewd apex
#

oh then alr

#

rip back to hhw sigh

spring flax
#

anyone know why this is not getting all members who are on timeout? ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
for members in disnake.utils.as_chunks(guild.members, 10_000):
for mem in members:
if mem.current_timeout:
self.timed_out.append(mem)
await asyncio.sleep(0.3)
print('Completed getting timeouted members')

maiden fable
spring flax
#

it's only showing one, but i'm sure there are more than one

shrewd apex
spring flax
#

where?

shrewd apex
#

print mem

spring flax
#

oh no

shrewd apex
#

oh wait a sec

spring flax
#

wait, am i just checking for the first 10,000 members?

shrewd apex
#

y for members in guild.members

spring flax
#

what do you mean?

shrewd apex
#

wont guild.members return a list already

spring flax
#

i need the list of members who are on timeout

#

i'm calling the func by a cog_load

shrewd apex
#

!d disnake.utils.as_chunks

unkempt canyonBOT
#

disnake.utils.as_chunks(iterator, max_size)```
A helper function that collects an iterator into chunks of a given size.

New in version 2.0.
maiden fable
#

[x for x in x.members if x.current_timeout]

#

Easy

slate swan
#

^

spring flax
#

I initially tried that

robust fulcrum
maiden fable
#

Well, then u can use a task

maiden fable
unkempt canyonBOT
robust fulcrum
shrewd apex
#

or threading

slate swan
spring flax
maiden fable
#

U should use a print statement

spring flax
#

Not error, I mean Not work

#

Print what?

shrewd apex
#

in if mem.on_timeout:

#

add print(mem)

spring flax
#

I have one when the loops complete

shrewd apex
#

do it in the loop we will know how many are timed out

#

or if the loop is even reaching there

spring flax
#

Okay

robust fulcrum
#

Replit db is bad

#

Use sqlite

#

Or any other

slate swan
#

!d discord.ext.commands.Bot.guilds

unkempt canyonBOT
slate swan
#

same

#

!d nextcord.ext.commands.Bot.guilds

unkempt canyonBOT
slate swan
#

no

robust fulcrum
#

I will start with hikari tommorow

slate swan
#

replit dbs is slow ngl

#

does anyone have a bot that uses cogs, that they made in DPY 2.0

#

that I could take a look at

maiden fable
#

Does db["Guild"] returns a string?

slate swan
#

sarth should get the gist pinged ngl

maiden fable
#

Can u print the type of that?

quick gust
#

bro

maiden fable
#

I'm out

quick gust
#

print type(db["Guild"])

slate swan
quick gust
#

bro

slate swan
quick gust
#

that's basic python

#

and it's alot easier to help when u know atleast the basic python

quick gust
#

in your code??????

slate swan
#

replits db is like a dict so its just like regular indexing lol

quick gust
#

no u use the print function

#

print(type(db["Guilds"]))

#

yeah so it's an int not string

#

I'm not sure what u were trying to do after this so I'll leave here lol

#

yeah no sorry idk a thing about slash commands

#

yes

#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
grand marlin
#

i'm trying ;; help? idk what i have been doing wrong. it's for a discord music bot

#

someone told me to do a coroutine but i had no idea how to do it

paper sluice
#

!ytdl

unkempt canyonBOT
#

Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.

For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:

The following restrictions apply to your use of the Service. You are not allowed to:

1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service;  (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;

3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;

9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
grand marlin
#

oh okay! ><

#

thank you anyway, sorry about that

spring flax
#

so I have ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
for members in disnake.utils.as_chunks(guild.members, 10_000):
for mem in members:
if mem.current_timeout:
print(mem.name)
self.timed_out.append(mem)
await asyncio.sleep(0.3)
print('Completed getting timeouted members')

this prints
```py
๖ۣۣۜA̸ᴍeꪀør # Just some dumb name
Completed getting timeouted members
#

but there are more names it should print

shrewd apex
#

maybe only person is timeouted

slate swan
robust fulcrum
#

@slate swan why you not participating in code jam?

#

You are pro at python

spring flax
slate swan
shrewd apex
#

380000 is not much

slate swan
#

not so much yeah

spring flax
#

it took a long time with list comprehension for some reason

slate swan
#

how much approx?

shrewd apex
#

maybe latency

spring flax
#

10-15 I think

shrewd apex
#

or slow internet

slate swan
paper sluice
#

[*filter(lambda x: x.current_timeout, guild.members)]

spring flax
#

well yeah...I did just only check it once

shrewd apex
slate swan
#

its actually faster than for loop ^

shrewd apex
#

if its memory problem maybe its better to use generators

paper sluice
shrewd apex
paper sluice
#

filter is implemented in c, so its going to faster

slate swan
#

ASscary just use c to make bots ez

spring flax
#

[*filter(lambda x: x.current_timeout, guild.members)] what is the return type of this?

paper sluice
#

list

spring flax
#

so what's the * for?

paper sluice
#

unpackning filter object

shrewd apex
#

map is fastest

spring flax
#

i can't use map here

shrewd apex
#

filter or for will roughly be same

paper sluice
#

!e

a = filter(lambda x: x%2, range(10))
print(a)
print([*a])
unkempt canyonBOT
#

@paper sluice :white_check_mark: Your eval job has completed with return code 0.

001 | <filter object at 0x7f9baf765540>
002 | [1, 3, 5, 7, 9]
paper sluice
shrewd apex
#

its same as list(filter())

shrewd apex
spring flax
#

thanks. So this is correct? ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
members = [*filter(lambda x: x.current_timeout, guild.members)]
for member in members:
print(member.name)
self.timed_out.append(member)

shrewd apex
#

but if for loop took 10 sec it wont magically become 2 or 3 with a filter

#

add a time.time and check the time it takes

paper sluice
slate swan
#

they are also checking member.name but that can be done later by printing the complete list too

shrewd apex
#

also in this case even if u need to append just use extend

#

why append one by one

spring flax
# paper sluice just do ```py self.timed_out = [*filter(lambda x: x.current_timeout, guild.memb...

class Timeouts(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.timed_out = []

    async def get_timeouts(self):
        await self.bot.wait_until_ready()
        guild = self.bot.get_guild(619762818266431547)
        for members in disnake.utils.as_chunks(guild.members, 10_000):
            for mem in members:
                if mem.current_timeout:
                    print(mem.name)
                    self.timed_out.append(mem)
            await asyncio.sleep(0.3)
        print('Completed getting timeouted members. Bot is ready')
#

then later I am doing ```py
@commands.command()
@needed_check()
async def timeouts(self, ctx):
if not self.timed_out:
description = "No members are currently on timeout"
else:
description = "\n".join(
[
f"{member.mention} ({str(member)} is on timeout until <t:{int(member.current_timeout.timestamp())}>)"
for member in self.timed_out
]
)

    embed = disnake.Embed(
        title=f"Members on timeout ({len(self.timed_out)})", description=description
    )
    await ctx.send(embed=embed)
paper sluice
#

then just do self.timed_out.extend([*filter...])

spring flax
#

oh okay

paper sluice
#

append would be very slow

shrewd apex
#

^^

paper sluice
#

+= might also be faster

shrewd apex
#

work with sets

#

much faster

paper sluice
#

right

spring flax
#

so += is faster than extend?

shrewd apex
#

wont cause much diff

#

if u really wanna check then add time.time() and check for all combos like for loop filter and all

spring flax
shrewd apex
#

!timeit

a = [1,2,3]
b = [4,5,6]
a.extend(b)
print(a)
unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your timeit job has completed with return code 0.

200000 loops, best of 5: 1.67 usec per loop
paper sluice
#

@spring flax whats the len of self.timed_out??

shrewd apex
#

!timeit

a = [1,2,3]
a += [4,5,6]
print(a)
spring flax
#

so - ```py
async def get_timeouts(self):
await self.bot.wait_until_ready()
guild = self.bot.get_guild(619762818266431547)
self.timed_out.extend([*filter(lambda x: x.current_timeout, guild.members)])
print([member.name for member in self.timed_out])
print('Completed getting timeouted members. Bot is ready')

unkempt canyonBOT
#

@shrewd apex :white_check_mark: Your timeit job has completed with return code 0.

200000 loops, best of 5: 1.67 usec per loop
shrewd apex
#

its same

spring flax
#

just printed one name

shrewd apex
spring flax
#

but

#

i'm looking at the audit logs and I see more

shrewd apex
#

they left or timeout is over

spring flax
#

can i send all my code?

#

if that helps

paper sluice
spring flax
#

i'm looking at the audit logs right now and it's telling me there are more than one users on timeout

vale wing
#

Metalimune seems like an interesting word

paper sluice
spring flax
spring flax
#

nobody has solutions?

loud junco
#

what is config['prefix']
and the intent is not defined?

pastel solar
loud junco
#

but what's that prefix

paper sluice
#

which lib?

pastel solar
paper sluice
#

did u run the bot?

pastel solar
paper sluice
#

do this

from discord.ext import commands

bot = commands.Bot(...)

@bot.command()
...

bot.run(...)
pastel solar
#

The slash commands and the other events work perfectly fine, only the prefix commands don't seem to work for me.

paper sluice
#

u need commands.Bot

pastel solar
supple cobalt
#

Man

loud junco
supple cobalt
#

Return and await commands are killing me

#

I just cant understand what’s the problem w it

#

Whenever i type return or await, it shows up as an error

loud junco
#

u need help?

supple cobalt
#

Rn, im on phone

#

If you want to help uh, could you wait for an hour?
I actually need help 😭

cerulean folio
#

Hi guys, someone knows why am I receiving this when I try to conenct my bot (and they don't connect)

shrewd apex
#

u spammed discord api with requests💀

slate swan
#

💀

cerulean folio
#

I mean... The previous bot never had this problem and I didn't particularily spam it x.x

#

I don't understand, what should I do now?

slate swan
#

it doesn't ban for no reason, as it says you've been banned for temporarily try waiting a few hours

cerulean folio
#

alright

#

thank you guys

shrewd apex
#

is ur bot too big or u have a very frequent task or something?

cerulean folio
#

both lmao

#

I'm embarrassed...

#

it's been used by like 5 or 6 people simultaneously the whole time

#

thing is that when i connect the bot from my pc it works no problem, but from replit it annoys me with rate limit thingie

paper sluice
spring flax
#

yes

paper sluice
#

the member that doesn't show up in the timeout list, check if they are in guild.members

spring flax
#

i did

#

i looked at the audit logs. It showed definitely more than one, and I checked if those they were showing were in the mutual guilds and it showed, so they are in

paper sluice
#

did their timeout end?

spring flax
#

no

paper sluice
#

manually check what member.current_timeout returns for that member(s)

spring flax
#

okay

modern fiber
#
@client.command()
@commands.is_owner()
async def shutdown(ctx):
    await ctx.respond('Shutting down.')
    exit()```

It doesn't seem to do anything when I do .shutdown?
#

It's supposed to stop running the bot.

#

Well maybe doesn't work because I am hosting it on heroku - yeah..

spare urchin
#

any help on this

slate swan
#

can someone throw me to the documentation line where there is info for creating/adding custom emoji

shrewd apex
jaunty wedge
spare urchin
#

;-;

shrewd apex
spare urchin
#

any changes there ?

jaunty wedge
#

Well i am on mobile rn so i cant possibly help

modern fiber
jaunty wedge
#

@spare urchin i will sed when i would be free

slate swan
#

anyone?

shrewd apex
shrewd apex
#

go there and slide the slider

spare urchin
shrewd apex
#

reason TEXT)")

#

yes

spare urchin
#

ok..

cerulean folio
slate swan
#

how do you add a custom emoji to your discord server

loud junco
slate swan
#

using python dpy

visual island
#

!d discord.Guild.create_custom_emoji

unkempt canyonBOT
#

await create_custom_emoji(*, name, image, roles=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

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

There is currently a limit of 50 static and animated emojis respectively per guild, unless the guild has the `MORE_EMOJI` feature which extends the limit to 200.

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

You can always see the docs, they have good function namings

slate swan
#

.
Hi

loud junco
slate swan
#
        cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
            id INT,
            name TEXT,

            work_1 INT,
            work_2 INT
            )""")

        for guild in self.client.guilds:
            for member in guild.members:
                if cursor.execute(f"SELECT id FROM cooldown WHERE id = {member.id}").fetchone() is None:
                    cursor.execute("INSERT INTO  cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', 1, 1))
                else:
                    pass
                conn.commit()

Dear, please tell me how to enter today's date in the value work _1

shrewd apex
#

SQL has a column type date use that

robust fulcrum
#

@shrewd apex you told me to get the perspective api key but till now from yesterday they have not sent me email of key

slate swan
supple cobalt
#

i

slate swan
#

?

swift pumice
#

do you guys know any free bot hosting websites?

paper sluice
supple cobalt
paper sluice
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

supple cobalt
#

oh

#

ahem

slate swan
#
    @commands.command(name = "BD2")
    async def comand_BD2(self, ctx):

        cursor.execute("""CREATE TABLE IF NOT EXISTS cooldown(
            id INT,
            name TEXT,

            work_1 timestamp,
            work_2 int
            )""")

        for guild in self.client.guilds:
            for member in guild.members:
                if cursor.execute(f"SELECT id FROM cooldown WHERE id = {member.id}").fetchone() is None:
                    cursor.execute("INSERT INTO  cooldown VALUES (?, ?, ?, ?)", (f'{member.id}', f'{member}', joining_date, 1))
                else:
                    pass
                conn.commit()
        await ctx.send("ДА")

Dear, I found material on the Internet about SQL date and time. but for some reason it didn't work for me. how to write down the date and time in the value please tell me.

supple cobalt
#
import discord, random

TOKEN = 'can't show you token<3'

client = discord.Client()

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

@client.event
async def on_message(message):
    username = str(message.author).split("#")[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username} : {user_message} ({channel})')

if message.author == client.user:
    return


if message.channel.name == "testing-1":
    if user_message.lower() == "hello":
        await message.channel.send == (f'Hello {username} !')



client.run(TOKEN)
#

okay finally

#

tell me why my await and return doesn't function

#

it gives me an error

paper sluice
#

both if statements are outside the function

#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

slate swan
supple cobalt
supple cobalt
paper sluice
slate swan
slate swan
slate swan
supple cobalt
#

OH

#

ty understood now

slate swan
#

Nice

#

😂 I literally copy pasted

#

the Ryuga's msg

supple cobalt
#

ik, i read both then looked at the function

slate swan
#

Oh good 👍

supple cobalt
#

thanks ryuga and sparky, im processing slowly ever since im learning to code

slate swan
#

Just make more commands in discord.py it will help u learn python more

#

also use cogs

#

So it will increase ur oop skills

#

That's how I learned

#

add a emoji

shrewd apex
#

Is there any simple function or command to hide cogs from the send_cog_help command

#
button = Button(emoji='', label='', style=discord.ButtonStyle.link, url=)
sullen pewter
cold tide
#

Anyone know the issue?

sullen pewter
#

indentation

cold tide
#

still learning.

sullen pewter
#

incorrect indentation

#

!indent

unkempt canyonBOT
#

Indentation

Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.

Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.

Example

def foo():
    bar = 'baz'  # indented one level
    if bar == 'baz':
        print('ham')  # indented two levels
    return bar  # indented one level

The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.

Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines

More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation

cold tide
#

@sullen pewter im on a android i cant use indent here

sullen pewter
#

4 spaces

cold tide
#

Wym?

#

Can you just show me what it should look like?

supple cobalt
#
import discord
import random


TOKEN = "can't show ya<3"

client = discord.Client()

@client.event
async def on_ready():
    print("We have logged in as {0.user}".format(client))

@client.event
async def on_message(message):
    username = str(message.author).split("#")[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username} : {user_message} ({channel})')  

    if message.author == client.User():
        return
    

    if message.channel.name == 'testing-1':
        if user_message.lower() == "hello":
            await message.channel.send == (f'Hello {username}!')
            return
        if user_message.lower() == "bye":
            await message.channel.send == (f'See ya later {username}!')
            return
        
            



client.run(TOKEN) 
#

ok

#

i gave it a command to say hello and bye

#

its not responding thoducky_angel

cold tide
#

waste of my time smh