#discord-bots

1 messages · Page 1062 of 1

flint isle
#

hmm the only error i have is


ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-3' coro=<startup() done, defined at C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py:111> exception=AttributeError("'NoneType' object has no attribute 'get_channel'")>
Traceback (most recent call last):
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 131, in startup
    location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
AttributeError: 'NoneType' object has no attribute 'get_channel'

tropic burrow
#

(dont judge me for using pickle, kinda the only option i could understand)
why does nothing display at all when i run this code:

import random
import discord
from webserver import keep_alive
import os
import requests
from discord.ext import commands
from discord.ext.commands import has_permissions
import urllib
import json
import pickle



class Data():
  def __init__(self, wallet, bank):
    self.wallet = wallet
    self.bank = bank

client = commands.Bot(command_prefix = "-monkey ")

datafilename = "data.pickle"
               
def loaddata():
  if os.path.isfile(datafilename):
    with open(datafilename, "rb") as file:
      return pickle.load(file)
  else:
      return dict()

def loadmemberdata(memberID):
  data = loaddata()

  if memberID not in data:
    return Data(0,0)
  return data[memberID]

def savememberdata(memberId, memberdata):
  data = loaddata()

  data[memberId] = memberdata

  with open(datafilename, "wb") as file:
    pickle.dump(data, file)
  
@client.event
async def on_ready():
    print("Bot is ready")

#clear messages

@client.command()
@commands.cooldown(1,5,commands.BucketType.user)
async def beg(ctx):
  memberData = loadmemberdata(ctx.author.id)
  earnings = random.randint(0,100)
  memberData.wallet += earnings
  mbed = discord.Embed(
    title="You beg other monkes for monkebux...",
    description=f"and got {earnings} monkebux!"
  )
  await ctx.channel.send(embed=mbed)
  savememberdata(ctx.author.id, memberData)

@client.command()
@commands.cooldown(1,5,commands.BucketType.user)
async def balance(ctx):
  memberData = loadmemberdata(ctx.author.id)
  mbed = discord.Embed(title="{member}'s balance is...".format(member=ctx.author.display_name))
  mbed.add_field(name="Monke Wallet", value=str(memberData.wallet))
  mbed.add_field(name="Monke Bank",value=str(memberData.bank))
  await ctx.channel.send(embed=mbed)
potent spear
tropic burrow
potent spear
#

aight

#

how are you trying to invoke a command?

tropic burrow
flint isle
# potent spear https://discord.com/channels/267624335836053506/343944376055103488/9769027933675...
async def startup():
    await bot.wait_until_ready()
    print('running startup embed')
    embed = disnake.Embed()
    embed.title = f"**Online**"
    embed.set_footer(text="Logging System")
    embed.set_author(name='WhiskeyBot', icon_url=f"{bot.user.avatar}")
    embed.description = f"""**Bot Startup and Information**
    Start Time: `{datetime.now().strftime('%b-%d-%Y at %I:%M:%S')} {timeofday}`
    Current Uptime: <t:{round(datetime.timestamp(start_time))}:R>
    Bot account: `{bot.user.name}`
    Bot ID: `{bot.user.id}`
    Guilds: `{len(bot.guilds):,}`
    Users: `{len(list(bot.get_all_members()))}`
    Disnake Version: `{disnake.__version__}`
    Loaded Cogs: `{list(bot.cogs)}`
    Developer: `whiskeythefox#7339`
    """
    GUILD_ID = 798726719573065749
    CHANNEL_ID = 798726720181633047
    location = bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
    await location.send(embed=embed)
bot.loop.create_task(startup())

thants my code. someone told me to not use on ready event for some reason

tropic burrow
#

at all

potent spear
slate swan
potent spear
heavy shard
#

but integer

potent spear
flint isle
#
running startup embed
<class 'int'>
heavy shard
#

ah right, didn't look there lol

potent spear
flint isle
#

yeah it should be

potent spear
unkempt canyonBOT
#

Hey @tropic burrow!

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

tidal hawk
#

By any chance is there a way when I kill process from terminal, the bot will send a message first that then it goes offline or smth

#

Like last script being run before shutting down

potent spear
#
    async def close(self):
        await super().close()
        await self.pool.close()
        await self.session.close()```
flint isle
#

it got kicked apparnely. but i cant get the oauth to work

#

it says i need a redirect uri

regal pulsar
unkempt canyonBOT
#
Nah.

No documentation found for the requested symbol.

heavy shard
regal pulsar
#

lmao

flint isle
#

curently i only have the bot one marked now

potent spear
potent spear
#

you're overwriting an existing method

#

you'll have to subclass your bot class

weak moat
#

Hello everyone, can someone tell me how to make an IT raid system, when more than n users log in in t minutes, then all n users are banned on the server

potent spear
potent spear
flint isle
jade tartan
#

Yes i do

potent spear
#

then you should understand

jade tartan
jade tartan
#

any way

flint isle
#

that was for someone else XD

jade tartan
#

But am not too sure what this one means

potent spear
#

X object has no attribute y I don't know if it could be more english than that

flint isle
# weak moat Yes

have you tried coding a simple bot yet. cause if you havent you should start there

weak moat
potent spear
weak moat
#

And why then do you criticize the actions, if you are in need of my help, like me?

regal pulsar
#

if it hits a certain amount then its spam

#

you dont even need a db just json is fine

#

you wont even need to separate by guild

heady sluice
sleek badge
#

Hi guys, how to make it so that if 10 users enter in 10 seconds, then these 10 users will be banned?

slate swan
visual island
# weak moat Hello everyone, can someone tell me how to make an IT raid system, when more tha...

This is probably a minimum code:

bot = commands.Bot(...)
bot.members_joined = []  # Initialize a botvar (list of Member object)

@tasks.loop(seconds=t)  # Create a tasks.loop which runs every t seconds
async def task():
  if len(bot.members_joined) > u:  #  Check if bot.members_joined length greater than u
    for member in bot.members_joined:  # Kick all the members
      await member.kick()
  bot.members_joined = []  # Reset the list

@bot.listen("on_member_join")  # Set up an on_member_join listener
async def foo(member):
  bot.members_joined.append(member)  # Add the member to our botvar
``` Please understand the code, not just copy-pasting
slate swan
#

member_join*

regal pulsar
regal pulsar
heady sluice
#

but I like the code

visual island
#

Better than not including any comment, or spoonfeeding

regal pulsar
#

not anti mass join ;)

slate swan
# regal pulsar because json :)

a dictionary will be fine for that purpose really, since the data aint gonna be useful later anyways, so its.....more resource wasting to be using json

flint isle
#

omg can someone help me with inviting my bot to my server after i kicked it

visual island
flint isle
potent spear
slate swan
#

^

flint isle
#

ok im there

regal pulsar
#

dev portal>applications>your bot>url generator>choose perms>copy url

#

someone send link to dev portal

flint isle
slate swan
maiden fable
slate swan
maiden fable
#

TIL this also works

flint isle
regal pulsar
#

the discord.dev domain

#

reminds me

slate swan
#

weird

regal pulsar
#

is there a library for discord games

maiden fable
#

Yea

heady sluice
regal pulsar
#

whats it called

#

i was thinking of making one

maiden fable
#

!pypi discordgame

unkempt canyonBOT
regal pulsar
#

perfect

heady sluice
#

what is this and how does it work

#

like voice channel games?

maiden fable
#

No

heady sluice
#

then

maiden fable
#

text based games

heady sluice
#

it's dum

regal pulsar
#

but one of the examples is snake

maiden fable
#

Agreed

regal pulsar
#

i mean those activity things in vc

maiden fable
#

Ah

heady sluice
#

can u even make those

maiden fable
#

!d discord.VoiceChannel.create_invite

unkempt canyonBOT
#

await create_invite(*, reason=None, max_age=0, max_uses=0, temporary=False, unique=True, target_type=None, target_user=None, target_application_id=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Creates an instant invite from a text or voice channel.

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

hmm

maiden fable
#

The application id and stuff

flint isle
#

ummm...

maiden fable
#

There's a blank for require code grant

regal pulsar
#

you clicked something you didnt need

flint isle
#

i tried using another bots invite and changing the client id

regal pulsar
#

wait a minute

#

!d disnake.Game

unkempt canyonBOT
#

class disnake.Game(name, **extra)```
A slimmed down version of [`Activity`](https://docs.disnake.dev/en/latest/api.html#disnake.Activity "disnake.Activity") that represents a Discord game.

This is typically displayed via **Playing** on the official Discord client.

x == y Checks if two games are equal.

x != y Checks if two games are not equal.

hash(x) Returns the game’s hash.

str(x) Returns the game’s name.
regal pulsar
#

oh nvm ;/

flint isle
#

@maiden fable

#

what should i select

maiden fable
#

Not here

#

On the General page

maiden fable
flint isle
regal pulsar
maiden fable
flint isle
maiden fable
#

Requires oAuth code grant

flint isle
#

omg

#

idk when i selected that

#

hmm my bots slash commands arent there yet

heavy shard
flint isle
#

i gave it admin. why so many declined perms?

heavy shard
#

no idea but Administrator overrides them all anyway

flint isle
#

    @commands.slash_command(name="removereaction", guild_ids=config)
    async def rmreaction(self, ctx, reaction: str = commands.Param('reaction_name', description='Your choice depicts what reaction will be removed', choices=['checkmark','furheart','both']), amount: int = commands.Param('how_many_messages', description="Your input depicts the number of messages who's reactions get removed.", min_value=0)):
        msgs = [message async for message in ctx.channel.history(limit=amount)]
        count = 0
        for amount in msgs:
            if reaction == 'checkmark':
                await amount.clear_reaction('✅')
                await amount.ctx_reply(f'cleared (checkmark) reaction^ (number {count} out of {amount} messages')
                count = count + 1
                return
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Message' object has no attribute 'ctx_reply'
flint isle
maiden fable
#

Yea

potent spear
flint isle
#

yeah. also how can i get the amount that is a number entered in as a int?

potent spear
#

int(message.content)

flint isle
#

use instead of sending (1 out of #) its sending:

(number 1 out of <Message id=978648470191743046 channel=<TextChannel id=798726720181633047 name='general' position=5 nsfw=False news=False category_id=798726719573065750 default_auto_archive_duration=1440> type=<MessageType.default: 0> author=<Member id=798201838867578940 name='WhiskeyBot [Beta]' discriminator='9603' bot=True nick=None guild=<Guild id=798726719573065749 name='WhiskeyBot Testing' shard_id=0 chunked=True member_count=15>> flags=<MessageFlags value=0>> messages)

potent spear
#

hint: enumerate

flint isle
potent spear
#

async for counter, msg in enumerate(ctx.channel.history(limit=amount)):

flint isle
#

does that replace the loop?

potent spear
#

yup

flint isle
#

ok

potent spear
#

also replaces msgs = ...

visual island
potent spear
#

exactly what I thought

#

it'll probably just need the "manual" counter (no enumerate)

#

but the async for remains

flint isle
#

you mean like counter =1
counter = counter +1

potent spear
#

+= 1

flint isle
#

oh that simplifies it

potent spear
#
counter = 0
async for msg in ctx.channel.history(...):
  counter += 1
  # ...```
flint isle
#

ight i got it working

#

    @commands.slash_command(name="removereaction", guild_ids=config)
    async def rmreaction(self, ctx, reaction: str = commands.Param('reaction_name', description='Your choice depicts what reaction will be removed', choices=['checkmark','furheart','both']), amount: int = commands.Param('how_many_messages', description="Your input depicts the number of messages who's reactions get removed.", min_value=0)):
        msgs = [message async for message in ctx.channel.history(limit=amount)]
        count = 1
        outof = amount
        for amount in msgs:
            if reaction == 'checkmark':
                await amount.clear_reaction('✅')
                await amount.reply(f'cleared (checkmark) reaction^ (number {count} out of {outof} messages')
                count += 1
                return
            ```
#

i had to add a var outof so it wouldnt get scrambled in the if statment

potent spear
#

still, your count doesn't make much sense

#

you should also async iterate, there's no reason to have a list of all already async iterated messages

potent spear
#

your code also contains a small illogical part

slate swan
#

whats the point of that count, that is just same as the length of msg var

  • it will send the cleared ( checkmark ) ... reply for each time it tries to clear the reaction
terse coyote
#

how to check member status
(if member.status == ...:
...)?

potent spear
terse coyote
#

yes

#

idk how to do this:

potent spear
#

well, first of all, what does member.status return?

#

This way, I'm also checking if you read the docs

terse coyote
potent spear
#

in the docs

#

seems like you don't know how to use them yet

spring flax
#

!d discord.Member.status

unkempt canyonBOT
#

property 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.10)") instead.
potent spear
#

^^

terse coyote
#

"The member’s overall status."
idle, online, offline, dnd, invisible...?

potent spear
#

mhm, it'll return one of those

terse coyote
#

that's what i wanted to say

potent spear
#

you'll need presences intents however to "keep track" of member's statuses

#

if you don't, it'll always return offline

terse coyote
#

I included them all a long time ago

potent spear
#

then you're good to go

terse coyote
terse coyote
potent spear
#

then it's just offline online, dnd, ...

#

try something out

#

I won't give you code examples ofc

maiden fable
#

!d discord.Status is what it's gonna return

unkempt canyonBOT
#

class discord.Status```
Specifies a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") ‘s status.
terse coyote
maiden fable
#

And it's an enum

potent spear
#

you can compare the enum it returns with a string

regal pulsar
slate swan
unkempt canyonBOT
maiden fable
#

Uhhh?

#

How do u think isinstance would work 🤨

#

Bro, the second arg needs to be a class

slate swan
#

wait

#

I'm dying

maiden fable
#

Haha I also thought of using isinstance first then realized it's not a class

slate swan
#

I will just go away

warped mirage
#

Guys can someone pls help me make a warn system on aiosqlite

#

I tried but it’s confusing L

maiden fable
#

Do u know the basic idea behind the same?

warped mirage
#

Oh damn hello Ashley again xd

warped mirage
slate swan
#

sqlite's giving me headaches

#

😭

#

how

warped mirage
slate swan
#

sqlite is so easy

warped mirage
#

Anytime works 🙂

slate swan
# slate swan sqlite is so easy

Ikr, but weirded errors such as not adding a comma at the end to make a tuple and being stuck there for 10 minutes isnt fun

slate swan
slate swan
slate swan
rocky hornet
#

how can i check if a command is currently running

warped mirage
#

Tbf js is so easy for databases

#

Like no cap

slate swan
warped mirage
#

Like const {} = require(“mongoose”)

#

As a decent example .

#

Py is good but confusing for some people but for me it’s 2x ss

rocky hornet
#

wut

rocky hornet
slate swan
rocky hornet
#

js is cringe

slate swan
#

staph

maiden fable
#

The cringiest thing in JS is ===

slate swan
#

If you're talking about SQL

maiden fable
#

And there's nothing difficult in calling a few methods

slate swan
#

its far better then having to typecast every value

#

being specific to discord api and databases, the only thing javascript is better at is speed~

heady sluice
#

voice receiving

slate swan
heady sluice
#

nextcord is bad

slate swan
#

!pip lavasnek-rs this too

unkempt canyonBOT
slate swan
#

!d discord.Message.attachments would return a list of attachments see if there's any image in it

unkempt canyonBOT
slate swan
#

uses the on_message event and check for attachments using the attachments property which returns a list of attachments and check if it has an image, then use the add_roles method on the Member object and pass in the Role object

rocky hornet
#

how can i check if a command is running?

slate swan
#

I've got an issue too 😔
whenever I store ids in a sqlite database, the last two digits of the ids are defaulted to 0 for no reason

#

though the user_id should be 925079016174682213 and the guild_id should be 946357178917330944

slate swan
#

use BIGINT

#

even tried using a BIGINT

#

does the same thing

#

thats weird cause it works for me, what library is that?

slate swan
#

which library, I mean

slate swan
slate swan
slate swan
#

aiosqlite

#

or the one danny made

#

it could be something related to your code as well..

#

like what? 😔

slate swan
#

!e ```py
print(round(123456789 , -2))

unkempt canyonBOT
#

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

123456800
slate swan
# slate swan !e ```py print(round(123456789 , -2)) ``` like This

nothing like that, all I have for inserting values is

async def create(self, user_id: int, guild_id: int, starting_xp: int=5, starting_level: int=1):
     _check = await self.read(user_id, guild_id)
     if _check:
        return self.named_tuple(_check[0], _check[1], _check[2], _check[3])
      await self.cur.execute('''INSERT INTO exps(user_id, guild_id, xp, level) VALUES(?, ?, ?, ?)''', (user_id, guild_id, starting_xp, starting_level,))
      await self.conn.commit()
      return self.named_tuple(user_id, guild_id, starting_xp, starting_level)
rocky hornet
#

imagine storing ids as ints lmao

slate swan
slate swan
#

python does not give you any

#

its still called that

#

they dont work like it but the community still names it constants

#

iirc even vsc names them constants

slate swan
slate swan
slate swan
slate swan
#

thats weird lemme recheck my dbs

#

sure thanks

warped mirage
#

Btw can someone help me

slate swan
slate swan
maiden fable
#

Weird, bigint should store the ID correctly

#

!e print(len("493451846543998977"))

unkempt canyonBOT
#

@maiden fable :white_check_mark: Your eval job has completed with return code 0.

18
maiden fable
#

Hmm

slate swan
#

trying to get the len of an int😭

slate swan
#

BIGINT(18)

honest laurel
slate swan
#

but it does not, i can show code + outputs

honest laurel
#

Discord id's a re 64 bit wide, why wouldn't it work?

#

I've been storing role ids and channel ids as bigint just fine

slate swan
#

do you just use BIGINT as the type, or BIGINT(18) ?

honest laurel
#

bigint

#

I use postgres, could try it with sqlite too though @slate swan

warped mirage
#

can someone help me work with my warn system using aiosqlite

honest laurel
#

@slate swan Could you send me the problematic id?

slate swan
#

it rounds off~, to the closest 100

honest laurel
#
class TestModel(Base):
    __tablename__ = "test_model"
    id = Column(BigInteger, primary_key=True)


def main():
    Base.metadata.create_all(engine)
    discord_id = 580034015759826944

    with Session.begin() as session:
        test_model = TestModel(id=discord_id)
        session.add(test_model)
        session.flush()
        session.refresh(test_model)
        assert test_model.id == discord_id
#
-- auto-generated definition
create table test_model
(
    id BIGINT not null
        primary key
);
slate swan
#

is that sqlalchemy?

honest laurel
#

Yep

slate swan
#

lemme show what happens with aiosqlite

honest laurel
#

I could try with aiosqlite driver

warped mirage
#

xd

solemn blade
warped mirage
#
@commands.command()
@commands.has_permissions(manage_messages=True) 
async def warn(self,ctx, user: discord.Member, *, reason=None):
    warn2= discord.Embed(title="Warning",description=(f'{user.mention} You are being warned for: {reason}'), color=0xEEA1FF)
    await ctx.send(embed=warn2)
    db = aiosqlite.connect("warn.db")
    cursor = client.db.cursor()
    cursor.execute(f"SELECT warn_counter FROM warned_info WHERE user = {user.id}")
    num=cursor.fetchone()[0]
    print(num)
    if num is not None:
        cursor.execute(f"UPDATE warned_info  SET warn_counter = {num + 1} WHERE user = {user.id} ")
    else:
         cursor.execute(f"INSERT INTO warned_info (user, warn_counter) VALUES ({user.id},{1})")
    client.db.commit()``` would this work lol
slate swan
# honest laurel I could try with aiosqlite driver
import asyncio

import aiosqlite


async def main() -> None:
    conn = await aiosqlite.connect("test.db")
    await conn.execute("CREATE TABLE test (id BIGINT)")
    await conn.commit()

    await conn.execute("INSERT INTO test VALUES ( ? )", (580034015759826944,))
    await conn.commit()

asyncio.run(main())
``` code ^
warped mirage
slate swan
#

!d discord.Member.add_roles *how to give member a role

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.
honest laurel
#

Maybe it's a problem with your db browser?

slate swan
#

appears fine in DB browser

slate swan
#

thank you! @honest laurel

warped mirage
slate swan
#

still weirded though cz whenever I query the db with the guild id, it returns None for some reason

warped mirage
#

Yo

#

Ashley when can u help me lol ig

slate swan
maiden fable
slate swan
warped mirage
#

Btw can I send my full code and can yall check if it would work as multi guild

#

Just as a checkup yet

slate swan
#

try it and see

#

we arent python interpreters

#

!d split

slate swan
warped mirage
#

Ok nvm I’m fine

#

All I need is just help with warn system

slate swan
#

how could I "separate" command names

#

i mean,for example:

@bot.command()
async def enable level(ctx):
    await ctx.send('pong')
slate swan
#

huh?

#
@bot.group()
async def enable(ctx):
  ...

@enable.command()
async def level(ctx):
  ...
#

oh okay, ty btw

honest laurel
#

To avoid having a large class with single group

slate swan
honest laurel
#

Why?

slate swan
#

I mean, first you'd get the cog, then you'd want to have something that gets the group constructor and then use that object to create a subcommand, dont even think thats possible practically

honest laurel
#

That's why i'm asking if there's another way

#

I might have a lot of subcommands or nested subcommands, so wanting to split them up isn't unheard of IMO

flint isle
#

ok so i have an await until a reaction is added. how can i have it respond if the reaction is already on the message

slate swan
#
if message.channel.id == ....:
    #Do something```
maiden fable
#

!d discord.Message.reactions

unkempt canyonBOT
maiden fable
#

Cool custom presence BTW Blank

slate swan
#

\👍

slate swan
maiden fable
#

This is what I see lol

swift imp
#

Why when I use a command with a cooldown, after giving an error about the absence of arguments, the cooldown works?py @bot.command() @discord.ext.commands.guild_only() @commands.cooldown(1, 3600, commands.BucketType.user) async def test(ctx, *, text): await ctx.send(f'The command worked: {text}')

I am sending:
!test
Bot:
Write Arguments
I send after this:
!test Message with arguments
Bot:
Whoa whoa whoa, you already used the command, wait a bit

slate swan
#

how can i loop through all commands in a specifc cog for a help command?

maiden fable
#

!d discord.ext.commands.Cog.get_commands @slate swan

unkempt canyonBOT
#

get_commands()```
Returns the commands that are defined inside this cog.

This does *not* include [`discord.app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command") or [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group")
instances.
slate swan
#

dont follow old code
its a Member object's method now

#

!d discord.Member.add_roles

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

Yo wsg I’m back now

#

Now I can get help

slate swan
slate swan
# slate swan code pls
async def all_guild_records(self, guild_id: int):
   return await (await self.cur.execute("SELECT * FROM exps WHERE guild_id = ?", (guild_id,))).fetchall()

''' and I call it using '''
await all_guild_records(context_guild_id)
#

even though there's a record with the same guild id

slate swan
slate swan
#

the INT, BIGINT thing

#

uhhh no

warped mirage
#

Btw before anything , I can have multiple async def setup_db(): ye ?

keen mural
#

Any1 have any idea how i could make a bot like rumble royale

#

Or heists in dank memer

slate swan
warped mirage
#

And must be multi guild if possible

slate swan
warped mirage
slate swan
warped mirage
#

The same way I did for level system ? But different I guess

warped mirage
swift imp
slate swan
warped mirage
#

I thinks it’s client.load_extension(“filename.py”) this is for the loading

slate swan
warped mirage
#

Btw are we able to make the warning system multi guild

slate swan
#

yes

warped mirage
#

Also

maiden fable
#

Just have one single universal table

slate swan
#

^

wet crystal
#

How am I able to check if the message.author is in a Voice Channel and then return the channel id?

warped mirage
#

I have a idea on the warn system so it could have
warn warns delwarn clearwarns

Would be cool but anything works

maiden fable
#

Well i have an idea for yr warn system

warped mirage
#

Here we go lol

maiden fable
#

If the same person is warned multiple times in many guilds, just add a universal warning. This will tell all the guilds that he has a bad image in other servers but idk, prolly gonna be a bit of an overkill

warped mirage
#

My bot is currently in a test server and my mates

#

So ye

slate swan
slate swan
maiden fable
maiden fable
slate swan
slate swan
maiden fable
#

U have impl this, but not the other person

slate swan
#

no?

warped mirage
slate swan
maiden fable
#

What's yr bot about

warped mirage
#

My bots a multipurpose i want it to have lots of minigames and systems but I’m runnin out of ideas , after I get help on warn system ima learn more of aiosqlite and develop stuff ig

slate swan
#

reason why i left bot dev because its all bland and boring

warped mirage
#

Omg POG idea make a warning leaderboard see who has most warns

maiden fable
#

oki I have a boring project idea for u @slate swan

slate swan
#

no

maiden fable
#

Nvm then

keen lynx
#
import pymongo

myclient = pymongo.MongoClient("xxxxxxxxxxxxxxxxxxxx")
mydb = myclient["spyboy"]
mycol = mydb["users"]

user = '729429813726543975'

if user in mycol.find({},{ "users_id": 1}):
    print("user is in db.")
else:
    print("user not in db.")
``` here trying to check if the user is in the database or not. even tho the given user in db still printing user not in db. no experience with mongodb lil help plz.
slate swan
warped mirage
slate swan
warped mirage
#

but i do want to code warn command , warnings check , delete warns [amount] and then clear command that clears all

maiden fable
placid skiff
#

Bruh?

slate swan
slate swan
placid skiff
slate swan
#

who says

placid skiff
#

Ash d.py requires an high knowledge of python D_D

maiden fable
#

I totally didn't start dpy without knowing what are functions

placid skiff
#

But you are smarter

warped mirage
maiden fable
slate swan
placid skiff
slate swan
warped mirage
#

ye doesnt help much but ill try

slate swan
maiden fable
slate swan
#

even an example doesnt help...?

warped mirage
#

idk ill try

quaint epoch
#

.topic

lament depotBOT
#
**What feature would you like to see added to the library? What feature in the library do you think is redundant?**

Suggest more topics here!

warped mirage
#

btw do multi guild stuff also work in cogs

maiden fable
quaint epoch
slate swan
warped mirage
#

ok good

placid skiff
placid skiff
#

An ESP32 is a good micro and it is a lot cheap, also components are not expensive

#

Back in school i did some cool project and one of them is even available to the public now

slate swan
placid skiff
slate swan
placid skiff
#

The fun fact is that assembly is the easiest part of using a PIC

wet crystal
#

is this gonna send the voicechannel ID of the user who called the command?

@bot.command
async def roulette(ctx):
    Test = nextcord.VoiceState.channel
    await ctx.send(Test)
slate swan
#

Raw VoiceState class is just a skeleton with no information about user

#

Access it's instance using.... umm... ctx.user.voice ig...

wet crystal
slate swan
#

Check if their voice state is none or not

#

!d discord.Member.voice

unkempt canyonBOT
formal basin
#

What does this error mean

heavy shard
#

just (before, after)

formal basin
#

Ok thanks

regal pulsar
#

i didnt know how to pass arguments 💀

heavy shard
#

functions and some basics of OOP are neccessary if you want to do something beside just blindly copying the code from examples

regal pulsar
#

so you dont need self

regal pulsar
#

i learnt classes with cogs

regal pulsar
#

who doesnt ;)

heavy shard
#

copy-paste and alter something? this is how i learned my first programming language

formal basin
#

What should I replace member with I can’t find anything in the Member object

heady sluice
formal basin
#

Oh really?

heady sluice
#

I would bet my life on it

formal basin
#

Ok

heady sluice
#

that's a pretty big async loop you got there

slate swan
#

So I want to make a command where it sends a number e.g 20 but if discord.CustomActivity is a certain thing it sends a different number any ideas? I know how to do it for role but not this hehe

flint isle
#

how can i check if my bot has a specific permission in a server?

slate swan
#

my bot's token suddenly stopped working, i literally regened the token, tried with other test bots and made a new bot and it says improper token passed??

heavy shard
slate swan
#

i would recommend using the commands.bot_has_permissions check if you are trying to check that for running a command..

tacit token
#

hi guys in pillow i how to delete black color in cutted profile picture?

slate swan
#

use png image formats instead of jpeg/jpg

tacit token
#

ok i try it ty

#

the problem is same

#

with png

halcyon onyx
#

hello

tacit token
#
@client.command()
async def bonk(ctx, user: discord.Member, user2: discord.Member = None):
    if user == None:
        user == ctx.author
    if user2 == None:
        user2 = ctx.author
    wanted = Image.open("bonker.png")
    asset = user.avatar_url_as(size=4096)
    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    pfp = pfp.resize((329, 256))
    wanted.paste(pfp, (255, 117))
    asset = user2.avatar_url_as(size=4096)
    data = BytesIO(await asset.read())
    pfp = Image.open(data)
    pfp = pfp.resize((287, 252))
    wanted.paste(pfp, (806, 511))
    wanted.save("bonked.png")
    await ctx.send(file=discord.File("bonked.png"))
halcyon onyx
#

i have bug and i cant fix it any one help?

#

here i unban the user i but (ctx, *, member) to pass every thing after the ctx to member and when the user have space in his username i get error 'takes 1 positional argument but 2 were given'

tacit token
#
@client.command(name='unban')
async def _unban(ctx, id: int):
    user = await client.fetch_user(id)
    await ctx.guild.unban(user)
#

try this

potent spear
#

you can just unban by user ID

#

user = discord.Object(id=...)

#

it might not verify that this user exists, but well...

#

checking by name and discriminator isn't the way to go: these values can both changes

sick birch
sick birch
#

Because that one is terrible

tacit token
#

how can i make a command who can send message to other channel what i mention. Example i try !send #mytestroom message
Bot send xyz channel xyz message

potent spear
sick birch
#

Shouldn’t be difficult; what do you have so far?

potent spear
#

the lovely world of dpy even converts the channel to a channelobject since you typehinted it

halcyon onyx
potent spear
sick birch
#

That looks exactly like the one from Lucas

#

Maybe someone pasted that into the stackoverflow from Lucas? That’s twice as bad

halcyon onyx
#

i saw one video of lucas i gotheadache

potent spear
#

so now you're reading them... lol

sick birch
#

Because the code you have is identical to his unban command

#

Why unban with O(n) time?

halcyon onyx
#

im using this now

sick birch
#

Can I see the full code now?

halcyon onyx
#

ok

#
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason=None):
        if reason == None:
            await ctx.guild.ban(member)
            await ctx.send(f"User {member.mention} has been banned for 'No reason provided'")

        else:
            await ctx.guild.ban(member)
            await ctx.send(f'User {member.mention} has been banned for {reason}')

    @commands.command()
    @commands.has_permissions(ban_members=True)
    async def unban(ctx, member_id = None):
        if member_id == None:
            print('Please enter the user id')
        else:
            await ctx.unban(discord.Object(id=member_id))```
#

ban and un ban

sick birch
#

Codeblock please

potent spear
#

close

sick birch
#

!code

potent spear
#

pretty funny ban command if you'd ask me lol

sick birch
#

For sure

halcyon onyx
#

at least it works 😂

sick birch
#

Just set the default argument to “No reason provided”

potent spear
#

then you can remove the if else

halcyon onyx
#

ohh nice

sick birch
#

It should really be like 2 or 3 lines max

halcyon onyx
#
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason='No reason provided'):
        if reason == None:
            await ctx.guild.ban(member)
            await ctx.send(f"User {member.mention} has been banned for {reason}")```
#

like this?

potent spear
#

remove the if else

exotic maple
#

How do i only print certain values ? from this

#

E.g it only prints TotalConfirmed

#

val

potent spear
#

python dict
at least, I suppose it's a string, else you'd have to convert it to a dict first

halcyon onyx
#
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member, *, reason='No reason provided'):
        await ctx.guild.ban(member)
        await ctx.send(f"User {member.mention} has been banned for {reason}")```
sick birch
#

There you go

#

2 lines is all it took

halcyon onyx
#

i think i will go with this style it's more readable

sick birch
#

Same deal with the unban

halcyon onyx
#

what best way to unban with id

sick birch
#

!d discord.Guild.unban

unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

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

hey, is there a way for a webhook to reply to a message it sent?

warped mirage
#

Guys I need help making a cog file first

potent spear
grand shell
# halcyon onyx yes

oh awesome! ive got the message object. how can i send a new message in response to that one

warped mirage
grand shell
exotic maple
#

can i show you my code?

halcyon onyx
#

and replay with it

potent spear
halcyon onyx
exotic maple
heady sluice
slate swan
unkempt canyonBOT
#

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

1 2 None
potent spear
slate swan
#

yea, thats important

potent spear
#

he's also not familiar with nested dicts, also tell him 😉

slate swan
#

if you will try to get the value of key using dict[key] and the key is not in the dictionary, a KeyError exception will be raised, while dict.get(key) will return None ( by default )

exotic maple
#

ill look else where

warped mirage
#

@potent spear I’ll need ur help soon

potent spear
tacit token
#

This command send only 1 word, why?

@client.command()
async def send(ctx, channel: discord.TextChannel,uzenet):
    uzenet = "".join(uzenet)
    await channel.send(f"{uzenet}")
tacit token
#

ok but again send 1 word only

potent spear
#

you need to read

#

the second codeblock in that link is EXACTLY what you need

tacit token
#

ty so much

keen mural
#

any1 know how i can make a bot like rumble royale or a command like dank memer heist

grand shell
#

hey, i cant seem to get a webhook to reply to a message. if you do await msg.reply(), the bot will reply to the message. how do i reply with the webhook? from what i can gather from the docs, webhooks only have the send() method

heady sluice
#

neither will you need the f-string

keen mural
#

how can i create a list of people who reacted to an emoji?

tidal hawk
#

Does somebody know: for how long can a user fill out Discord Textinput (forms), without expriing?

#

Like I tested it, and after 10 minutes it gave me an error

#

but the timeout is not listed anywhere

#

Or is it just interaction.response which is timing out

slate swan
#

do you mean Modals or is it some new thing?

tidal hawk
#

Na the TextInput

slate swan
#

!d discord.TextInput

unkempt canyonBOT
#

class discord.TextInput```
Represents a text input from the Discord Bot UI Kit.

Note

The user constructible and usable type to create a text input is
[`discord.ui.TextInput`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.TextInput "discord.ui.TextInput") not this one...
tidal hawk
slate swan
#

pWut thats a Modal with TextInput items in it.

tidal hawk
#

Oops

slate swan
#

!d discord.ui.Modal

unkempt canyonBOT
#

class discord.ui.Modal(*, title=..., timeout=None, custom_id=...)```
Represents a UI modal.

This object must be inherited to create a modal popup window within discord.

New in version 2.0...
slate swan
#

see the timeout kwarg

tidal hawk
#

ye

#

thanks, didn't realise that

#

bruh now i feel dumb xD

tacit token
#

can i put img to my embed from my computer? example embed.set_image(url="asd.png")?

slate swan
#

yes, but

#

!local-file this way

unkempt canyonBOT
#

Thanks to discord.py, sending local files as embed images is simple. You have to create an instance of discord.File class:

# When you know the file exact path, you can pass it.
file = discord.File("/this/is/path/to/my/file.png", filename="file.png")

# When you have the file-like object, then you can pass this instead path.
with open("/this/is/path/to/my/file.png", "rb") as f:
    file = discord.File(f)

When using the file-like object, you have to open it in rb mode. Also, in this case, passing filename to it is not necessary.
Please note that filename can't contain underscores. This is a Discord limitation.

discord.Embed instances have a set_image method which can be used to set an attachment as an image:

embed = discord.Embed()
# Set other fields
embed.set_image(url="attachment://file.png")  # Filename here must be exactly same as attachment filename.

After this, you can send an embed with an attachment to Discord:

await channel.send(file=file, embed=embed)

This example uses discord.TextChannel for sending, but any instance of discord.abc.Messageable can be used for sending.

terse coyote
#

how to get guild without ctx?

slate swan
#

!d discord.Message.guild

unkempt canyonBOT
slate swan
#

!d discord.ext.commands.Bot.get_guild

unkempt canyonBOT
terse coyote
#

why are not all members logged into bd?
mongodb

#

guild: 55 members
db: 20 members

warped mirage
#

File "C:\Users\Dom\Desktop\beta test\cogs\utils.py", line 4, in <module>
class utils(commands.cog):
TypeError: module() takes at most 2 arguments (3 given) guys i have a problem with cogs

keen mural
#

instead of py await interaction.response.send_message('Cancelling', ephemeral=True) what can i do to make it so it doesnt say interaction failed even when it does when i want it to do

warped mirage
slate swan
#

no code no help

warped mirage
#

cog file

#

bot.py ```py
client.load_extension('utils')

for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f'cogs.{filename[:-3]}')```

green bluff
#

How would I get client as a member object

slate swan
#

and stop using client name for bot.

wet crystal
#

!d discord.VoiceState.channel

unkempt canyonBOT
#

The voice channel that the user is currently connected to. None if the user
is not currently in a voice channel.

green bluff
keen mural
#

how can i rerun my code without closing out of vs code

warped mirage
wet crystal
warped mirage
#

Had to be cogs.utils

keen mural
wet crystal
#

!d user

keen mural
#

ctx.author

wet crystal
#

Why does the error Command "roulette" is not found pop up when using $roulette?

import nextcord
from nextcord.ext import commands

bot = commands.Bot(command_prefix='$')
TOKEN = "Token"

@bot.event
async def on_ready():
    print(f"{bot.user.name} booted up succesfully!")

@bot.command
async def roulette(ctx):
    Test = str(nextcord.VoiceState.channel)
    await ctx.send(Test)

bot.run(TOKEN)
wet crystal
sand salmon
#
@client.command()
async def Timer(ctx, *, seconds):
    seconds = int(seconds)
    await ctx.reply(f'Timer for {seconds} seconds initiated')
    for i in range(seconds, 0, -1):
        time.sleep(1)
    await ctx.reply('The timer has ended!')```
How can I make this not block any other command until the timer has ended
drowsy pendant
#

+d help

sick birch
#

#bot-commands

sick birch
#

Also you know you can pass in the # of seconds to asyncio.sleep() instead of running a for loop sleeping for 1 second

#

also typehint your seconds to int, and d.py will auto int it for you

sand salmon
#

the loop was for something else I removed

sick birch
#
@bot.command()
async def timer(ctx: commands.Context, seconds: int):
  ...
sand salmon
#
@client.command()
async def Timer(ctx, *, seconds: int):
    await ctx.reply(f'Timer for {seconds} seconds initiated')
    asyncio.sleep(seconds)
    await ctx.reply('The timer has ended!')```
this doesn't sleep the program and the timer ends instantly
#
  asyncio.sleep(seconds)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
slate swan
#

you forgot to await asyncio.sleep

sand salmon
#

oh

#

fuck

vocal snow
#

What would happen if the if statement inside the for loop never triggered

#

What would the value of team be

#

No, the variable would be undefined.. which is why you get that exception

wet crystal
#

can you use text styles like these Hey, My, name, is Frey
in embeds?

#

if yes, how?

#

Just wanted to be sure

#

alright

#

if anyone has time it would b nice If you could look into here #help-pie

potent spear
#

on it

slate swan
#

embed = discord.Embed(title="test", description=f"[{ctx.author.mention}], You do not have access to execute this command!", colour=ErrorColour)

jolly rock
#

Check ur indentation for the lines above it and if u can’t see anything redo ur indentation

#

Python sometimes acts weird and puts random spaces for me

dull terrace
#
teams = ("Arizona Cardinals", "Atlanta Falcons", "Baltimore Ravens", "Buffalo Bills", "Carolina Panthers", "Chicago Bears", "Cincinnati Bengals", "Cleveland Browns", "Dallas Cowboys", "Denver Broncos", "Detroit Lions", "Green Bay Packers", "Houston Texans", "Indianapolis Colts", "Jacksonville Jaguars", "Kansas City Chiefs", "Las Vegas Raiders", "Los Angeles Chargers", "Los Angeles Rams", "Miami Dolphins", "Minnesota Vikings", "New England Patriots", "New Orleans Saints", "New York Giants," "New York Jets", "Philadelphia Eagles", "Pittsburgh Steelers", "San Francisco 49ers", "Seattle Seahawks", "Tampa Bay Buccaneers", "Tennessee Titans", "Washington Football Team")

@slash.slash(name="demand", description="Demands yourself from the team you're signed to")
async def demand(ctx):
  if any(role in teams for role in ctx.author.roles):
      team = role
  else:
      await ctx.reply('You are not signed to a team!')
sick birch
dull terrace
#

but i was bored robin sadcat

#

gimmie something to code 😤 - also i just realised that code wouldn't work

hollow agate
#
    time = datetime.now(tz=pytz.timezone('America/Tijuana'))
    with open("transcripts.html", "w", encoding="utf-8") as file:
        msg = [message async for message in ctx.channel.history(oldest_first=True, limit=1)]
        firstmessagetime = msg[0].created_at.strftime("%m/%d/%y, %I:%M %p")``` How could I make the `firstmessagetime = ` use the `time = ` timezone?
slate swan
potent spear
hollow agate
potent spear
#

step 1 is to get the time variable's timezone

#

step 2 is to use astimezone on the created_at attribute (since created_at returns a datetime object) gotta love that, no?

hollow agate
#

Oh, I see, thank you!

potent spear
#

also check this out
!d discord.TextChannel.history.flatten

#

hmm, just know that the history method has a flatten method, I'll link it

#

second example is what you need

#

only reason why you'd iterate through it explicitly if if you wanted to check something for every message or whatever

#

there's also not a good reason to open the transcripts file while you're still doing other shit

get all your variables ready
open file
write to it
done (closing happens by itself ~implicitly~ thanks to context manager with open(...) as f: )

slate swan
#

👋

slate swan
#

anyone Know how many inivtes you can make per second?

sick birch
#

Why?

dusky pine
sick birch
#

No, but it goes against the spirit of the server

azure nebula
#
@bot.command()
@has_permissions(manage_messages=True)
async def unmute(ctx, member:discord.Member, reason=None):
  role = discord.utils.get(ctx.guild.roles, name="aislados")
  await member.remove_roles(role)
  await ctx.send(f'El usuario {member} ha sido desmuteado por ``{reason}``')

@unmute.error
async def unmute_error(ctx, error):
  if isinstance(error, commands.MissingPermissions):
    await ctx.reply("No tienes permiso de unmutear!")```
azure nebula
keen mural
#

!d discord.Role.members

unkempt canyonBOT
keen mural
#

try that

azure nebula
#

ok

stone beacon
#

There's a @spring wadi_role decorator @azure nebula

smoky cedar
#

I have a question yall, I have a discord bot I've made, it uses slash commands, but it also runs a task every minute. If someone attempts to use a command while the bot is running the task, the command will fail. How can I solve this? Do I need to have the bot running multiple threads?

slate swan
#

Like what type of task?

smoky cedar
visual island
#

What's inside the task? Why does the slash commands fail if the task is running?

slate swan
#

whats inside the task

smoky cedar
#

Just code that sends a new spotify release if an artist has a new song, The slash commands fail because the bot is busy executing this code and cannot accept the task

slate swan
#

Is there anything blocking in the task?

#

like time.sleep or something

smoky cedar
slate swan
#

can you send the code

smoky cedar
#
@tasks.loop(minutes=1)
async def send_new_releases():
    artists = db.get_all_artists_from_db()
    for artist in artists:
        channel_id = db.get_music_channel_id_for_guild_id(artist.guild_id)
        channel = client.get_guild(int(artist.guild_id)).get_channel(int(channel_id))
        if channel is None:
            continue
        artist_role = channel.guild.get_role(int(artist.role_id))
        if artist_role is None:
            db.remove_artist_from_db(artist.name)
            continue
        newest_release = get_newest_release_by_artist_id(artist.id)
        if newest_release is None:
            continue
        newest_release_id = newest_release['id']
        # If we haven't already notified the channel of this release
        if artist.latest_notified_release != newest_release_id:
            db.set_latest_notified_release_for_artist_id(artist_id=artist.id, new_release_id=newest_release_id)
            release_url = newest_release['external_urls']['spotify']
            message = await channel.send("<@&%s> New Release!\n:white_check_mark:: Assign Role."
                                         ":x:: Remove Role.\n%s" % (artist.role_id, release_url))
            await add_role_reactions_to_message(message)
smoky cedar
#

I need the bot to be able to execute slash commands while also executing this method constantly

#

Multiple threads right?

slate swan
#

I don't know about the db module but I think it is probably blocking the code. Try not to use tasks.loop but a new thread

#

use the async library for what you are using, or use run_in_executor

smoky cedar
#

or just constructing a db instance independently in each method?

slate swan
#

probably could be an issue, try using threading

smoky cedar
#

I'm not sure if it's db since here in this:

@slash.slash(
    name=SET_COMMAND,
    description="Use in the desired channel to receive updates",
)
async def set_update_channel(ctx: SlashContext):
    message = await ctx.send("Attempting to configure current channel for updates...")
    if not db.is_guild_in_db(ctx.guild_id):
        db.add_guild_to_db(ctx.guild_id, ctx.channel_id)
        await message.edit(content="Current channel successfully configured for updates. "
                       f"You may begin following artists using `/{FOLLOW_COMMAND}`.")
    else:
        db.update_guild_channel_id(ctx.guild_id, ctx.channel_id)
        await message.edit(content="Current channel successfully configured for updates.")
#

I can't even get the first message to send

#

Even though it is before anything db related

slate swan
#

eh seems like a lot of blocking stuff, what database is that?

smoky cedar
#

mysql

slate swan
#

!pip aiomysql use this instead

unkempt canyonBOT
smoky cedar
slate swan
#

this won't block your code while using the database

smoky cedar
#

But the bot still doesn't accept commands while it is executing

jade tartan
slate swan
unkempt summit
#

Guys, quick question. Is it possible to integrate a play to earn game inside discord?

#

Its like a turn based rpg game but instead of actual animation, there are lines that will say something like "Pirate sustained 63 damage", etc.

slate swan
#

lol nvm, yes it is

#

can anyone help with kahootpy here?

slate swan
#

kay

bright jetty
#

where i can host i can pay

honest laurel
bright jetty
#

a discord bot

honest laurel
#

contabo is pretty cheap, otherwise you can use something like vultr, digital ocean, linode, etc

#

if you want a vps with full access

bright jetty
#

Does it work cause i really connect it on ip based token on a game

honest laurel
#

I'm not sure what you mean

bright jetty
#

ip-based token like roblox cookie or else

#

ima just host it with vm

honest laurel
bright jetty
#

whats vps

honest laurel
#

Basically a vm that you rent

bright jetty
#

is it better than virtual machine

#

oh alr

bright jetty
honest laurel
#

Just check it yourself

bright jetty
#

i mean where i can get it or what type vps

bright jetty
#

ight thx i guess

unkempt summit
slate swan
unkempt summit
honest laurel
#

Only if it's not against discord tos

#

tehnically possible though

slate swan
#

trust issues, and i dont think discord allows something like that

unkempt summit
spice adder
#
@client.command()
@commands.has_role('Manager')
async def members(ctx, arg):
  members = await guild.fetch_members(limit=None).flatten() 
  matchingmembers = [x for x in members if x.name == str(arg)]
  for member in matchingmembers:
      print(member)
```Trying to make a command to print all members matching a name, but this comes back with `Command raised an exception: AttributeError: 'NoneType' object has no attribute 'fetch_members'` so I assume that I'm using the wrong term for it, but I don't know what the right one would be
spice adder
#

client.get_guild(817114023727857694)

honest laurel
#

It's none

#

meaning it probably does not exist

#

or bot wasn't fully loaded when you called it

spice adder
#

Hm, I'm copying the guild ID and it's still 817114023727857694

honest laurel
#

Where did you call get_guild?

spice adder
#

In main

honest laurel
#

Bot wasn't loaded then

#

try calling it in on_ready hook or in command itself

spice adder
#

Worked, that's odd

honest laurel
#

It's not

spice wadi
#

can someone help me with this error

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    import music
  File "/home/runner/musicot/music.py", line 16, in <module>
    if ctx.voice_client is None:
AttributeError: 'int' object has no attribute 'voice_client'
@commands.command()
async def join(self,ctx):
 if ctx.author.voice is None:
   await ctx.send("You're not in a voice channel!")
   voice_channel = ctx.author.voice.channel
if ctx.voice_client is None:
    voice_channel.connect()
else:
    ctx.voice_client.move_to(voice_channel)
jagged adder
#

can anyone tell me why this pause command isn't working?

#checks
PAUSE_STATE = False

@bot.event
async def on_message(message):
 
    if message.channel.id not in (x, x):
        return

    if message.author == bot.user:
        return

    if message.content.upper == "PAUSE":
        PAUSE_STATE = True
        return
    if message.content.upper == "RESUME":
        PAUSE_STATE = False

    if PAUSE_STATE:
        return

    if message.content.startswith("Play"):
        #time.sleep(3)
        await message.channel.send("**Act One, Scene One: The Beginning**")

im trying to stop the code from continuing past this point if PAUSE_STATE == True

#

but its continuing to accept inputs lower down the on_message function

slate swan
#

!return

unkempt canyonBOT
#

Return Statement

When calling a function, you'll often want it to give you a value back. In order to do that, you must return it. The reason for this is because functions have their own scope. Any values defined within the function body are inaccessible outside of that function.

For more information about scope, see !tags scope

Consider the following function:

def square(n):
    return n*n

If we wanted to store 5 squared in a variable called x, we could do that like so:
x = square(5). x would now equal 25.

Common Mistakes

>>> def square(n):
...     n*n  # calculates then throws away, returns None
...
>>> x = square(5)
>>> print(x)
None
>>> def square(n):
...     print(n*n)  # calculates and prints, then throws away and returns None
...
>>> x = square(5)
25
>>> print(x)
None

Things to note
print() and return do not accomplish the same thing. print() will only print the value, it will not be accessible outside of the function afterwards.
• A function will return None if it ends without reaching an explicit return statement.
• When you want to print a value calculated in a function, instead of printing inside the function, it is often better to return the value and print the function call instead.
Official documentation for return

slate swan
spice wadi
#

u mean the console?

keen mural
#

How could i make a bot like rumble royale or smth like a dank memer heist

#

i just dont understand the concept

spice wadi
#

no

torn sail
#

Then you don’t need self

#

As a parameter

spice wadi
#

oh u meant the class music or what

#

i dont get it

visual island
azure nebula
#

how can i dm the user?

warped mirage
#

@slate swan I setup a basic cog and a command works

#

So now we can code the rest

slate swan
warped mirage
#

Later?

slate swan
#

wdym

warped mirage
#

Like help later?

slate swan
#

yes later, sorry

warped mirage
#

Ok

slate swan
unkempt canyonBOT
#
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Sends a message to the destination with the content given.

The content must be a type that can convert to a string through `str(content)`.
If the content is set to `None` (the default), then the `embed` parameter must
be provided...
azure nebula
#

could you give a quick example?

slate swan
azure nebula
#

Thanks

drifting arrow
#

Can someone help me? I want to use buttons to cycle through a list of embs. Basically when they hit 'Next' it goes to the next embed and so on.
But i literally have no idea with buttons lol

slate swan
#

why when i did pip install disnake

#

.-. anyone

quaint epoch
#

!d disnake.ui.View

unkempt canyonBOT
#

class disnake.ui.View(*, timeout=180.0)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
slate swan
#

?

quaint epoch
#
embeds = list()
current_emb = 0

class view(disnake.ui.View):
  
  @disnake.ui.button(label="Next!")
  async def next(self, button: disnake.ui.Button, inter: disnake.Interaction):
    if current_embed != len(embeds)+1:
      current_embed += 1
      await message.edit(embed=embeds[current_embed-1])

  @disnake.ui.button(label="Back!")
  async def back(self, button: disnake.ui.Button, inter: disnake.Interaction):
    if current_embed != 0:
      current_embed -= 1
      await message.edit(embed=embeds[current_embed-1])
message = await ctx.send(embed=embeds[current_embed])``` should work
#

@drifting arrow

drifting arrow
#

i'll give that a crack

jade tartan
quaint epoch
slate swan
quaint epoch
#

disnake is superior

slate swan
quaint epoch
#

boutta inherit from BaseException

slate swan
quaint epoch
#

lets se

#

e

slate swan
#

...

quaint epoch
slate swan
#

hm alr

#

let me try

quaint epoch
#

the IT solution

#

and also, your ide may take some time to recognize modules, so restart it

jade tartan
#

Hello

quaint epoch
#

my ide takes ages

#

it practically doesn't

slate swan
#

@quaint epoch rip

#
The term 'c:/Users/hp/Desktop/bot/venv/Scripts/python.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the s
pelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:2
+ & <<<<  c:/Users/hp/Desktop/bot/venv/Scripts/python.exe c:/Users/hp/Desktop/bot/main.py
    + CategoryInfo          : ObjectNotFound: (c:/Users/hp/Des...ipts/python.exe:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
#

i deleted the venv

#

folder

drifting arrow
#

Now to figure out why my embs arent going into a list ;-;

#

such horrors

vale wing
#

Guys how can this thing happen: message.author from on_message is an instance of User although the message was sent in the server? Doesn't happen all the time but just sometimes. Required intents are enabled

jade tartan
#

Hello Can Someone Help Me Please

vale wing
#

Create a new venv before ofc

vale wing
slate swan
vale wing
#

Ok cool install them globally and restart IDE

#

And switch interpreter to global one

slate swan
#

um alr

slate swan
vale wing
#

Or ctrl+shift+p -> select interpreter

slate swan
#

so i goto where i installed python

vale wing
#

No tf

slate swan
#

huh

vale wing
#

VSC

slate swan
#

listen

vale wing
#

Your project folder

slate swan
#

😐

vale wing
#

Uh

#

Enter your python executable path

slate swan
#

ye thats what i said

latent sable
#

how to do this in python
someone will send a message and reply to him on the bot but without prefix

slate swan
#

alr let me add

vale wing
#

I thought a different thing sorry lol

vale wing
slate swan
vale wing
#

If you want commands

#

If you want to keep the prefix for commands and reply to other messages use on_message event

vale wing
slate swan
#

ye ig

vale wing
#

Try it out

#

If it works then it is a correct one

slate swan
#

works fine now the imports are also fine :)

#

thanks :>

drifting arrow
#

\o/ I think I figured something out!

drifting arrow
# quaint epoch ```py embeds = list() current_emb = 0 class view(disnake.ui.View): @disnak...

Didnt quite use this but it did give me an idea.

class altresults(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None
        self.pages = []
        self.pagenumber = 0
        self.users = []
        
    def setpages(self, number):
        self.pages = number
        
    def setusers(self, myusers):
        self.users = myusers
        
    @discord.ui.button(label='Previous', style=discord.ButtonStyle.red)
    async def previous(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.pagenumber == 0:
            self.pagenumber = self.pages - 1
        else:
            self.pagenumber = self.pagenumber - 1
        embed = self.setembed(self.pagenumber)
        await interaction.response.edit_message(embed=embed, view=self)
    
    @discord.ui.button(label='Next', style=discord.ButtonStyle.green)
    async def next(self, interaction: discord.Interaction, button: discord.ui.Button):
        if self.pagenumber == (self.pages - 1):
            self.pagenumber = 0
        else:
            self.pagenumber = self.pagenumber + 1
            
        embed = self.setembed(self.pagenumber)
        await interaction.response.edit_message(embed=embed, view=self)
        
    def setembed(self, pagenumber):
        print(pagenumber)
        print(self.users)
        embed = discord.Embed(title=f"{self.users[pagenumber]}")
        embed.add_field(name=f"{self.users[pagenumber]}", value=f"{self.users[pagenumber]}", inline=False)
        return embed

Probably a bit redundant to use pagenumber when I can count users instead 🤔

#

i mean pages*

#

But it works \o/

#

Now all I gotta do is fill in the rest

light violet
#
def exchange_code(code):
  data = {
    'client_id': CLIENT_ID,
    'client_secret': CLIENT_SECRET,
    'grant_type': 'authorization_code',
    'code': 'secret',
    'redirect_uri': REDIRECT_URI
  }
  headers = {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  r = requests.post('%s/oauth2/token' % API_ENDPOINT, data=data, headers=headers)
  r.raise_for_status()
  return r.json()
  
def add_to_guild(access_token, userID):
    url = f"{API_ENDPOINT}/guilds/940206335667101737/members/750015265135263835"
    botToken = os.getenv('tucan')
    data = {
    "access_token" : access_token,
    }
    headers = {
    "Authorization" : f"Bot {botToken}",
    'Content-Type': 'application/json'
    }
    response = requests.put(url=url, headers=headers, json=data)
    print(response.text)

code = exchange_code('secret code cant show')['access_token']
add_to_guild(code,750015265135263835)```

i am getting bad request pls help
slate swan
#
Ignoring exception in command None:
disnake.ext.commands.errors.CommandNotFound: Command "t" is not found
Unhandled exception in internal background task 'timer'.
Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python38\lib\site-packages\disnake\ext\tasks\__init__.py", line 157, in _loop
    await self.coro(*args, **kwargs)
  File "c:\Users\hp\Desktop\bot\giveaway.py", line 71, in timer
    for keys in logs2.keys():
RuntimeError: dictionary changed size during iteration

i want to loop it again

 @tasks.loop(seconds=5)
    async def timer(self):
         with open("giveawaytime.json") as f:
          logs2 = json.load(f)
          for keys in logs2.keys():
            a = logs2[keys]
            b = datetime.fromisoformat(a[0])
            if b <= datetime.now():
                a1 = a[1]
                a2 = a[2]
                await self.endgiv(int(keys),int(a1),int(a2))
                del logs2[keys]
                with open("giveawaytime.json","w") as s:
                 json.dump(logs2,s)

i know its the issue of del but how can i do this

maiden fable
#

!d dict.copy

unkempt canyonBOT
#

copy()```
Return a shallow copy of the dictionary.
maiden fable
#

Save it in another variable, then loop

warped mirage
#

can someone help me

maiden fable
#

Sure

warped mirage
#

ok

#

i need help with the warn system

#

i did setup a cog but now time for the code

#

@maiden fable possible or nah

maiden fable
warped mirage
#

But like can I get a confirm if ur able to help

maiden fable
#

Well, as I said, I won't be able to help u write all the code but solve yr doubts and stuff

#

I will be able to help if I am online lol

warped mirage
#

How long is it gonna take to rewrite ur bot

#

Do u have a lot ?

slate swan
# maiden fable use a copy of the dict

hm like this?

    @tasks.loop(seconds=5)
    async def timer(self):
         with open("giveawaytime.json") as f:
          logs2 = json.load(f)
          copy2 = logs2.copy()
          for keys in copy2.keys():
            a = copy2[keys]
            b = datetime.fromisoformat(a[0])
            if b <= datetime.now():
                a1 = a[1]
                a2 = a[2]
                await self.endgiv(int(keys),int(a1),int(a2))
                del logs2[keys]
                with open("giveawaytime.json","w") as s:
                 json.dump(logs2,s)
maiden fable
slate swan
#

alr leme test

sullen pewter
#

how to make user input after bot sends a certain message
For instance
Bot asks for a nickname
after user enters their nickname bot assigns it to them

unkempt canyonBOT
#
Not in my house!

No documentation found for the requested symbol.

maiden fable
#

!d discord.Client.wait_for

unkempt canyonBOT
#

wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Waits for a WebSocket event to be dispatched.

This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
sullen pewter
#

ty

slate swan
cloud dawn
warped mirage
#

wait guys

#

from bot.py import client into a cog

#

would this work?

cloud dawn
#

No

warped mirage
#

how can i fix it then so client is defined in a cog

cloud dawn
#

Pass the value

warped mirage
#

wdym

cloud dawn
#
class Test(Cog):
    def __init__(self, bot: Bot) -> None:
        self.bot = bot
slate swan
warped mirage
#

ok good

#

ima try code the db part and if anything i can always get support

#

@slate swan i need help defining

#

but also , would this work

visual island
warped mirage
#

Add this again ? Under the setup db

vale wing
#

Your cog object in its functions is self

#

Ah wait

#

It is outside of the cog

#

My apologies

visual island
# warped mirage So the self.client = client

No, as I said

take client as the function's parameter

For example:

async def setup_db(client):
    client.db = ...
``` Then in somewhere else (probably your bot's `setup_hook`) do
```py
await setup_db(client)
``` Where `client`, in this case, is your `Bot` instance.
vale wing
#

I'd recommend subclassing the bot and putting the setup actions to setup_hook method

visual island
#

Oh, but looking at the add_cog, it is not awaited, so, it's not the master branch and setup_hook isn't there yet.

vale wing
#

Then overwrite start

#

Afaik start is called only once

maiden fable
#

istg rewriting my bot sucks

#

I just realized how messed up everything was

vale wing
#

Same