#discord-bots

1 messages · Page 946 of 1

supple crescent
#

how could i make it so when someone tries to use a comd on cooldown, it dms them? i have the cooldoqwn cmd i just dont know how i would turn it into a dm?

@bot.event
async def on_command_error(ctx, error, member : discord.Member, *, content: str):
    content = "***Command on cooldown, please try again in {:.f} seconds!".format(error.retry_after)
    member=ctx.author
    await bot.send_message(member, content)
dull terrace
#

Sure either

dry kelp
#
import discord
from discord.ext import commands

class Event(commands.Cog):

    def __init__(self, spooky):
        self.spooky = spooky

    @commands.Cog.listener()
    async def on_user_update(self, before, after):
        
        guild = self.spooky.get_guild(guild_id)

        users_ids = before.id
        members = guild.get_member(users_ids)

        role = members.guild.get_role(role_id) 

        list = ['1', '2', ...]  #add as many as u want here... doesn't really matter

        if any(elem in members.name for elem in list):
            await members.add_roles(role) 
        else:
            await members.remove_roles(role) 


def setup(spooky):
    spooky.add_cog(Event(spooky))

@slate swan @sonic lintel

slate swan
slate swan
dull terrace
supple crescent
lucid vine
#

yea

slate swan
dull terrace
#

Yeah remember to await it

lucid vine
#

@slate swancan u assist me here

dull terrace
#

And he defined it as member okimii

sonic lintel
#

Thank you! @dry kelp does it recognise status of a user?

dry kelp
#

lemme see if it's possible

supple crescent
#
@bot.event
async def on_command_error(ctx, error, member : discord.Member, *, content: str):
     thing = "***Command on cooldown, please try again in {:.f} seconds!".format(error.retry_after)
    await Member.send(content=thing)
```, thats it?
slate swan
dry kelp
#

that one checks the user name

sonic lintel
#

basically it is supposed to recognise the vanity link

cloud dawn
slate swan
lucid vine
dry kelp
sonic lintel
#

how then?

dry kelp
#

give me a sec to modify it x)

sonic lintel
#

tysm!

dry kelp
#

@sonic lintel dms

slate swan
#

why?

#

just why help in dms

supple crescent
#
@bot.event
async def on_command_error(ctx, error, member : discord.Member, *, content: str):
    await Member.send(content="   Command on cooldown, please try again in {:.f} seconds!".format(error.retry_after))
dull terrace
#

I do that all the time to make it clearer to read

lucid vine
supple crescent
#

ahh

#
@bot.event
async def on_command_error(ctx, error):
    await Member.send(content="   Command on cooldown, please try again in {:.f} seconds!".format(error.retry_after))

that work?

lucid vine
#

no one can help me tho?

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

Sends a message to the destination with the content given.

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

To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`File`](https://discordpy.readthedocs.io/en/master/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.

To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Embed`](https://discordpy.readthedocs.io/en/master/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
slate swan
#

!d discord.ext.commands.Context.author

unkempt canyonBOT
slate swan
#

makes sense?

dull terrace
#

ctx.author.send now

lucid vine
#

@dull terrace
u know why this is happening?
ok so i made a cog and it worked fine but then i realised the commands i added had like prefixes with like async def _ping

ect fast forward i removed the _ now it doesnt work with the prefix for my server like i do myprefix(cmd)

supple crescent
dull terrace
lucid vine
# slate swan wdym it doesnt work

the prefix isnt being used like if i do _ which is my normal set prefix then the command in the cog it says in console no command thats called ping or something exists but if i add like async def _ping and do _ping it works but like its like the cog doesnt know my prefix you know

lucid vine
#

the name of what

lucid vine
slate swan
lucid vine
slate swan
dull terrace
#

I think there's a variable in the cog that is name="your command name"

lucid vine
#

the cog has 600 lines

slate swan
#

!paste

unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

lucid vine
#

or i mean where does that arg go

dull terrace
#

In the doodad above the function

lucid vine
#

there

dull terrace
#

Decorater

#

@command.command(name="leave", other stuff)

#

If I'm not mistaken

lucid vine
#

@commands.command(help="Summon me in a VC", aliases = ["summon"])

#

but thats just the aliases

slate swan
lucid vine
pliant gulch
#
from __future__ import annotations

import typing

import os
import cursecord

TOKEN = os.environ["DISCORD_TOKEN"]


async def main() -> None:
    async with cursecord.CursedClient(TOKEN) as (client, gateway, rest):

        @gateway.on(cursecord.MESSAGE_CREATE)
        async def message(message: cursecord.Message) -> typing.Iterator[str]:
            yield f"I got {message}"

    await client.connect()


asyncio.run(main())
```mmmm this is looking pretty cursed already
lucid vine
#

you can set it like _prefix dadadada.

slate swan
cloud dawn
cloud dawn
#

!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)
lucid vine
#

i dont need help with the coede

dull terrace
lucid vine
#

i need help with cogs

#

and the prefix

pliant gulch
#

I decided not to force having you to yield and shit everywhere

cloud dawn
lucid vine
#

same thing doesnt work

#

i need assistance

pliant gulch
#

I know it's kind of bad but I actually kind of like how this looks

#

TIme to troll

lucid vine
slate swan
lucid vine
#

it was just a test cmd

cloud dawn
lucid vine
#

regardless of the code its not associated with the code

#

i repeat i dont need help with ytdl

slate swan
cloud dawn
#

I don't really mind, maby someone else will help you in this channel.

lucid vine
lucid vine
#

dont use it otherwise

#

but yh anydays i need help with another cog called ping AnimeNod

dry kelp
#

@cloud dawn

#

dms rq

cloud dawn
slate swan
#

i still dont understand why dm users for help

#

you have so many general helpers here and you want to dm only one of them? why not just get multiple help

cloud dawn
unkempt canyonBOT
cloud dawn
#

!d disnake.Activity

unkempt canyonBOT
#

class disnake.Activity(**kwargs)```
Represents an activity in Discord.

This could be an activity such as streaming, playing, listening or watching.

For memory optimisation purposes, some activities are offered in slimmed down versions:

• [`Game`](https://docs.disnake.dev/en/latest/api.html#disnake.Game "disnake.Game")

• [`Streaming`](https://docs.disnake.dev/en/latest/api.html#disnake.Streaming "disnake.Streaming")
dry kelp
#

disnake?

cloud dawn
dry kelp
#

lemme check pycord

boreal ravine
#
import discord 

client = discord.ext.commands.Bot()

client.run(TOKEN)
``` why am i getting a missing argument error?
supple crescent
slate swan
#

?

supple crescent
slate swan
#

what about the message

boreal ravine
final iron
slate swan
pliant gulch
#

Everybody doing april fools already but it hasn't even hit april first for me

#

😔

slate swan
#

same

supple thorn
slate swan
#

astgopher

pliant gulch
#

20:49 utc -4

supple crescent
#

how would i define member, i cant seem to get it to work

@bot.event
async def on_command_error(ctx, error, member : discord.Member, *, content: str):
     oops ="Command on cooldown, please try again in {:.f} seconds!".format(error.retry_after)
    await Member.send(content= oops)
slate swan
supple crescent
boreal ravine
supple crescent
#

🗿

pliant gulch
#

Your signature shows member

#

Also does the error handler even get member?

#

I thought it was only ctx and error

supple crescent
#

i rly hate when i miss things like that

pliant gulch
supple crescent
#

never got that one b4 lol

supple crescent
#

ah that part must have been outdated ig

undone wyvern
#

What do we say... do I change my auto documented code on pypi to this? (Generated following the new PEP 9001 standers) ```py

coding=UTF-8-NOBOM

      import discord  ;import  aiofiles  ;import asyncio  ;
      from  textwrap import dedent;
      class  DocGen   :
  
  sync  def __init__(  self  ,bot  ):

self . bot= bot ;

  async  def  generate_docs(  self  ,  command  ) -> None:

async with aiofiles . open ( 'docs.md', 'a' ) as file :
await file . write( dedent ( f'\n Command Name: {command.name}\n **Command Description: {command.help}\n <br>\n <br>\n ') ) ;

  sync def document_code ( self  ) :

sync  def wrapper ( func)  :

asyncio . run( self. generate_docs ( func ) ) ;

return wrapper ;
dull terrace
#

I can now procrastinate on coding slash commands for my old bot

slate swan
supple crescent
slate swan
#

!pep 9001

unkempt canyonBOT
#
PEP not found

PEP 9001 does not exist.

pliant gulch
slate swan
#

bro

dull terrace
#

Why does everything start with spaces

slate swan
#

its pep 9001 code style

dull terrace
#

That's horrific

undone wyvern
slim ibex
#

&pep 9001

dim ruinBOT
#
**PEP 9001 - The Final Style Guide for Python Code**
Status

Provisional

Created

01-Apr-2022

Type

Standards Track

supple crescent
#
@bot.event
async def on_command_error(ctx, error):
     oops ="Command on cooldown, please try again in {:.1f} seconds!".format(error.retry_after)
    await member.send(content= oops)

memeber not defined ugghhhh whyy

slate swan
#

bro

supple crescent
#

fuck no thatds wrong

slim ibex
#

@pliant gulch why did you inadvertently add anonymous lifetimes to python: *_: Any

slate swan
#

the function doesnt take 2 arguments just use the author attr in the Context class which it returns a Member obj which the Member class has the .send method

slim ibex
pliant gulch
#

Yes I know what lifetimes are

slim ibex
#

oh wait i forgot

#

i literally talked to you about making a rust app

#

💀

pliant gulch
#

Kek, ```rs
pub struct Lexer<'a> {
source: &'a str,
}

slim ibex
#

🗿

supple crescent
dull terrace
#

It should work unless it doesn't have the author attribute

supple crescent
#

🫂

#

thanks

dull terrace
supple crescent
#

so much

dull terrace
#

You're welcome

slate swan
#

well we told you since like 20mins agodead

dull terrace
flint dome
#

so i have my bot scanning for somthing threw a api and i want to in one embed send a list of found objects how would i do that?

upbeat gust
#

What's your question

flint dome
#

so here an example

upbeat gust
#

Just add them to a string and set that as the desc

#

Or add fields for each

flint dome
#

hm one sec

hazy prawn
#

can someone assist

final iron
#

Deindent it

hazy prawn
#

that hits a second error

final iron
#

Which is...?

supple thorn
#

you just posted your token

hazy prawn
#

i just reset it

final iron
#

Yeah because you're doing async with message.channel.typing(): and not putting anything after

hazy prawn
#

wait a minute is that whats flagging it?

final iron
#

Flagging what

hazy prawn
#

tysm

#

anyone got an idea how to prevent a bot from going offline

sick birch
hazy prawn
#

i'll give it a shot, thanks

north garden
#

how to solve this error

#
import discord
import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot(debug_guilds=[881207955029110855])

@bot.event
async def on_ready():
    print(f"{bot.user} is ready and online!")

@bot.slash_command(name = "hello", description = "Say hello to the bot")
async def hello(ctx):
    await ctx.send("Hey!")

bot.run(os.getenv('TOKEN')) # run the bot with the token
``` here is my code
sick birch
#

You'll have to import commands too

#

from discord.ext import commands

north garden
#

thanks

ashen jacinth
#

Not sure if I'm in the wrong place, but I have a question. I am trying to make a program using the requests modal that can use / commands. I've looked for awhile, but I can't find anything. Does anyone know how?

solar summit
ashen jacinth
solar summit
sonic lintel
#

does anyone know how to host on replit? When I host on replit the bot stays online, but the code doesnt run at all but when I host locally on my computer the bot works fine

solar summit
sonic lintel
silent ermine
#

Did you get the token

sonic lintel
#

yeah no errors

sonic lintel
silent ermine
#

do you also have an on_disconnect

sonic lintel
#
from flask import Flask
from threading import Thread

app = Flask('')

@app.route('/')
def main():
  return "Your bot is alive!"

def run():
    app.run(host="0.0.0.0", port=8080)

def keep_alive():
    t = Thread(target=run)
    t.start()```
sonic lintel
umbral night
#

does any body know how to use discohook?

sonic lintel
#

yes

silent ermine
#

and did you do import keep_alive

umbral night
#

im not sure how to do something like this

sonic lintel
#

yes

silent ermine
sonic lintel
#

yep

silent ermine
#

like where bot.run

silent ermine
sonic lintel
#

HELP its a vanity bot

#

so it removed the link

#

give me a second

silent ermine
sonic lintel
#

sigh

umbral night
#

@silent ermine would u have any clue?

silent ermine
silent ermine
#

check the docs maybe

umbral night
#

oh ok

sonic lintel
#

Ill dm it to you

silent ermine
daring olive
#

hey

#

remove the invite url

sonic lintel
silent ermine
unkempt canyonBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

daring olive
#

or use that pastebin yeah

#

also, keep_alive scripts. ToS breaking? or no?

silent ermine
#

Just keeps the bot running

#

I dont think so but it should be fine

daring olive
#

i've heard conflicting things...

silent ermine
#

mainly*

daring olive
#

yeah i know

silent ermine
daring olive
#

but i would have assumed it breaks their terms

solar summit
#

why would it

daring olive
#

though i did hear one person say otherwise. i'll look into it now

#

bc replit offers paid tiers for those "always on" services

silent ermine
silent ermine
#

its weird but uh if its against ToS @sonic lintel i cant help you

sonic lintel
#

is it?

#

against the tos

silent ermine
sonic lintel
#

ok

daring olive
#

we can research together :) but yeah i'm looking

sonic lintel
#

if it is Ill host it another way :DD

sonic lintel
#
import logging
import discord
import keep_alive
from discord.ext import commands

logging = logging.getLogger('Discord')
print ("loading...")

spooky = commands.Bot(
    command_prefix=".",
    intents=discord.Intents.all(),
    case_insensitive = True,
    help_command=None,
    )

@spooky.event
async def on_ready():
    print("Hello World!")

@spooky.event
async def on_presence_update(before, after):

    if before.guild.id != 955214423323197450:
        return

    role = before.guild.get_role(958975642395897867) 
    log_channel = spooky.get_channel(958975903839428668)

    list = [""]

    if any(elem in after.activity.name for elem in list if after.activity is not None):
        
        embed_proceed = discord.Embed(
            title = "**This server has a new supporter!**", 
            description = f"**{after}** just represented us ! ✦﹒﹑Put in your status to get the following perks ! role and gain additional entries to giveaway and access to a cool chat! 。ᘒ", 
            color= discord.Color(0xADD8E6)
        ).set_image(url="https://media.discordapp.net/attachments/804978370050916362/958948387351306270/unknown.png?width=2160&height=246")

        await after.add_roles(role)
        await log_channel.send(embed=embed_proceed)
    else:
        await after.remove_roles(role)

keep_alive.keep_alive()
spooky.run(bot_token)```
silent ermine
#

Not keep_alve.keep_alvive()

sonic lintel
silent ermine
abstract kindle
#

Any tips to store bucketcooldowns when the bot goes offline or a cog is reloaded?

sonic lintel
#

loading...
Traceback (most recent call last):
File "main.py", line 44, in <module>
keep_alive()
TypeError: 'module' object is not callable

silent ermine
sonic lintel
abstract kindle
#

Because as of right now, if I reload the cog that the command is in or the bot goes offline, the cooldown is reset

sonic lintel
#

ok Ill see if it works Ill stop hosting it locally

silent ermine
#

Yep @daring olive it does not break any ToS

silent ermine
sonic lintel
#

still no

silent ermine
sonic lintel
#

ik

silent ermine
#

I also do not know about replit as I self host so

silent ermine
abstract kindle
#

Any way to save the cooldown when the bot goes offline or if the cog is reloaded? I suppose I could just put it into the cog reloading code, but what about the bot going offline?

sonic lintel
#

ok Ill try to figure it out lol

silent ermine
#
  • why would you need to if you do get the bot offline
#

its not like they can use it

abstract kindle
#

So that when it goes online, it could restore their cooldowns

#

I have a daily command for my economy bot, and everytime i do more testing / reloading, the cooldown gets reset for everyone

dull terrace
#

manual cooldowns with saving IDS in files

silent ermine
abstract kindle
#

Okay, I'll ask someone else

#

Thanks though

silent ermine
daring olive
#

i read thru replit's terms and didn't see anything explicitly disallowing keep_alive (i read the "prohibited" section and only skimmed the rest). so will let you guys know if i read or see otherwise

silent ermine
#

Or make a testing bot

daring olive
#

but now, for your standard PSA: don't use replit for hosting ;)

silent ermine
heavy folio
#

no it doesnt

silent ermine
daring olive
#

relevant pin

abstract kindle
#

This is a bot that I'm coding for me and my friends. I don't want them to use daily every time I reload the bot, as I will probably be working on this for a long time.

silent ermine
silent ermine
#

Like a loop every 24 hours checking if you can use the command

slate swan
#

drip what version and how to i install

silent ermine
lament mesa
#

the os module is in the standard library

silent ermine
#

Just import os and your good to go

wicked lily
#

hello what should i do here?

#

hello

silent ermine
wicked lily
#

i don't know what to do here

wicked lily
silent ermine
slate swan
silent ermine
#

Or anything relevant to it

wicked lily
#

is this some coding server or what?

silent ermine
wicked lily
#

nope

#

heheh

silent ermine
wicked lily
#

just kidding i do know what this is

silent ermine
#

You can virtually ask anything as long as it’s not against the rules and tos

#

And the tos of what you are using

wicked lily
#

ok fine

slate swan
wicked lily
#

ok

slate swan
wicked lily
#

bye

silent ermine
slate swan
silent ermine
wicked lily
#

:duck_joe_salute:

silent ermine
#

Imma head to bed gn ppl

slate swan
#

how can u change the color of the letters in os or u cannot?

#

of your discord client?

slate swan
boreal ravine
#
bot = getattr(getattr(__import__("discord"), "ext", "commands").Bot(command_prefix="h!")

cmd = getattr(bot, "command")
event = getattr(bot, "event")

@cmd()
async def ping(ctx):
    send = getattr(ctx, "send")
    await send("pong")

@event
async def on_message(msg):
    await msg.reply(msg.content)

getattr(bot, "run")("token")
``` Why ping command not working
slate swan
#

thats your ide?

#
@slash.slash(name="Demand", description='Demanding')
async def demand(ctx, role: discord.Role):
    await user.remove_roles(role)
    embed=discord.Embed(title="Demand Completed", description=f" You have Demanded from {role.mention}")
    await ctx.send(embed=embed)```
abstract kindle
#

probably means you need to import os

slate swan
#

why wont this work

#

!d discord.Member.remove_roles

abstract kindle
#

because its this

unkempt canyonBOT
#

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

Removes [`Role`](https://discordpy.readthedocs.io/en/master/api.html#discord.Role "discord.Role")s from this member.

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

oh nvm lol

#

I suppose for now I could just manually do cooldowns and have it write the date and time of when it was used to the database and then compare it to that each time...

slate swan
dull terrace
#

how do you guys use whitespace / blank lines?

#

or how often

#

i mean within functions

slate swan
#

I just use a single space line where ever I feel like

#

and later format it with black

dull terrace
#

so basically just use it to organise until the thing is done

#

same thing im doin right now

slate swan
#

yea

sick birch
austere solstice
#

it only stores 1 use like -ban dabby and -ban lorenz it will only store lorenz not dabby pls help

sick birch
#

Don't use JSON as a database

#

That's the best course of action

austere solstice
#

@sick birch can you help with it?

#

nvm started working

#

just changed to

await ctx.send(str(loads['action']))
sick birch
#

Yeah

#

That's the correct syntax

austere vale
#
async def nickname(self, ctx, user : nextcord.Member, *, nickname=""):
        nickname = nickname.strip()
        if nickname == "":
            nickname = None
        try:
            await self.bot.change_nickname(user, nickname)
            await self.bot.say("Done.")
        except nextcord.Forbidden:
            await self.bot.say("I cannot do that, I lack the "
                "\"Manage Nicknames\" permission.")

what do i put instead of change_nickname?

sick birch
#

Are you following a tutorial?

austere vale
#

ye they used change_nickname but i got that error when i ran it

sick birch
#

Well, don't

#

Because for one, change_nickname is not a thing, say() is not a thing. It was outdated a looong time ago

austere vale
#

what should be used instead of change_nickname then?

sick birch
#

The first thing to do is stop following that tutorial

#

It represents yourself. It has methods that you can perform on yourself

#

You're probably interested in the edit() coroutine of discord.ClientUser

#

Also, what's the point of this:

nickname = nickname.strip()
  if nickname == "":
    nickname = None
#

Why not just make nickname a required argument and catch it with an error handler?

#

Also, if this code is exactly the same as whoever made the tutorial, they're doing a pretty bad job, no offense

austere vale
#
async def nickname(self, ctx, user : nextcord.Member, *, nickname=""):
        nickname = nickname.strip()
        if nickname == "":
            nickname = None
        try:
            await user.edit(nick=nickname)
            await ctx.send("Done.")
        except nextcord.Forbidden:
            await ctx.send("I cannot do that, I lack the "
                "\"Manage Nicknames\" permission.")

how do i fix this?

sick birch
#

Well your bot says it

austere vale
#

they have administrator though

sick birch
#

Also I recommend you get rid of

        nickname = nickname.strip()
        if nickname == "":
            nickname = None

and make nickname a required argument

#

Are you the owner of the server?

#

Or is your role higher than the bot's?

austere vale
#

im the owner

sick birch
#

That's why

austere vale
#

ohh is that why

sick birch
#

Yes, that's why

austere vale
#

if i were to make it a required argument, how do i set it so that it removes the nickname if there is nothing?

sick birch
#

Oh. Then you might wanna set it to None

austere vale
#

oo oki

sick birch
#
async def my_command(ctx, arg: someTypehint = None):
  if arg:
    # user provided it
  else:
    # user did not provide it
ashen jacinth
austere vale
#

ty

solar summit
ashen jacinth
#

I have not heard the term "discord library", can you please define it? The reason why I asked here is because I wasn't sure where to ask. It does automatically work with discord, but as a user instead of a bot.

torn sail
#

User bots are not allowed

vast gale
maiden fable
#

Nope

upbeat gust
#

can't do anything related to interactions

buoyant zodiac
#
afkdict = {}

@bot.command()
async def afk(ctx, *, message="No message provided"):
    global afkdict

    afkdict[ctx.message.author] = message
    await ctx.send(f"**{ctx.author.mention}** i set your AFK")
    await ctx.author.edit(nick=f'[AFK] {ctx.author.name}')
    msg = await bot.wait_for('message', check=lambda message: message.author == ctx.author)
    await msg.reply(f"**{ctx.author.mention}** welcome back!")
    await ctx.author.edit(nick=ctx.author.name)
@bot.event
async def on_message(message):
    global afkdict
    if message.author in afkdict:
       afkdict.pop(message.author)

    for mention in message.mentions:  
        if mention.id != message.author:
          return
        if mention.id in afkdict:  
                afkmsg = afkdict[member]  
                await message.channel.send(f"**{member}** is currently AFK")
    await bot.process_commands(message)
``` when i ping the afk user nothing happens
wild oxide
#

how to make a playing status using python for discord bots

buoyant zodiac
#

!d discord.Game

unkempt canyonBOT
#

class discord.Game(name, **extra)```
A slimmed down version of [`Activity`](https://discordpy.readthedocs.io/en/master/api.html#discord.Activity "discord.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.
maiden fable
unkempt canyonBOT
#

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

Changes the client’s presence.

Example

```py
game = discord.Game("with the API")
await client.change_presence(status=discord.Status.idle, activity=game)
```   Changed in version 2.0: Removed the `afk` keyword-only parameter...
buoyant zodiac
#

No clue, j what i saw when i looked it up.

maiden fable
#

@buoyant zodiac what is that on_message?

buoyant zodiac
#

I was tweaking with it to see if any of the ways i thought of would work.

maiden fable
#

What u even tryna do in it

buoyant zodiac
#

If the member they ping is afk, the bot replies to them, and tells them the user is AFK.

maiden fable
#

Why u popping then?

buoyant zodiac
#

Thats if the user is afk, and comes back/types a message.

maiden fable
#

U should pop in the wait_for then

buoyant zodiac
#

hm, okay.

#

for mention in message.mentions:
or
for member in message.mentions:

maiden fable
#

?

buoyant zodiac
#
@bot.event
async def on_message(message):
    global afkdict
    for member in message.mentions:  
        if member.id != message.author:
          return
        if member.id in afkdict:  
                afkmsg = afkdict[member.id]  
                await message.channel.send(f"**{member}** is currently AFK: {afkmsg}")
    await bot.process_commands(message)
```?
sly hamlet
#
    @app_commands.command(name='leave')
    @commands.has_permissions(manage_guild=True)
    async def _leave(self, interaction: discord.Interaction):
    
        
        """Clears the queue and leaves the voice channel."""

        if:
            return await interaction.response.send_message('Not connected to any voice channel.')

        await interaction.guild.voice_client.stop()
        del self.voice_states[interaction.guild.id]
        await interaction.response.send_message(f"Left :)")``` ```py
Traceback (most recent call last):
  File "C:\Users\culan\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 791, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 846, in exec_module
  File "<frozen importlib._bootstrap_external>", line 983, in get_code
  File "<frozen importlib._bootstrap_external>", line 913, in source_to_code
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
  File "C:\Users\culan\OneDrive\Desktop\echo slash\cogs\testmusic.py", line 358
    if:
      ^
SyntaxError: invalid syntax

I seem to be having a problem with this area the command although I'm not able to figure it out I've been working on it for a bit I'm just unable to figure out where the invalid somatic is I understand that's pointing to write where that if statement is but I do not see anything wrong can someone help

buoyant zodiac
#

if what?

sly hamlet
#

That the issue is near the if statement

buoyant zodiac
#

you need an if something, like

if channel is None:
supple thorn
maiden fable
supple thorn
#
if statement:
    ...
slate swan
#

He wants that change to occur globally

buoyant zodiac
#
@bot.command()
async def afk(ctx, *, message="No message provided"):
    global afkdict

    afkdict[ctx.message.author.id] = message
    await ctx.send(f"**{ctx.author.mention}** i set your AFK")
    await ctx.author.edit(nick=f'[AFK] {ctx.author.name}')
    msg = await bot.wait_for('message', check=lambda message: message.author == ctx.author)
    afkdict.pop(message.author.id)
    await msg.reply(f"**{ctx.author.mention}** welcome back!")
    await ctx.author.edit(nick=ctx.author.name)
@bot.event
async def on_message(message):
    global afkdict
    for member in message.mentions:  
        if member.id != message.author:
          return
        if member.id in afkdict:  
                afkmsg = afkdict[member.id]  
                await message.channel.send(f"**{member}** is currently AFK: {afkmsg}")
    await bot.process_commands(message)
maiden fable
#

U r correct @slate swan

maiden fable
buoyant zodiac
#

Nope

slate swan
buoyant zodiac
#

Scroll up, its up there.

maiden fable
#

@buoyant zodiac add debug prints to see which line is getting executed and which is not

buoyant zodiac
#

Is there a way i can use jsk to see?

maiden fable
#

Every other line

slate swan
#

try

maiden fable
#

Same thing

#

!e

a = {1:2}
print(1 in a)
print(1 in a.keys()) 
unkempt canyonBOT
#

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

001 | True
002 | True
slate swan
sly hamlet
#

With the new interactions am I still able to do the typing feature? like this? async with channel.typing():

latent ember
#

How to make an discord bot alert in the discord when someone leaves it?

maiden fable
unkempt canyonBOT
#

discord.on_member_join(member)``````py

discord.on_member_remove(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/master/api.html#discord.Member "discord.Member") join or leaves a [`Guild`](https://discordpy.readthedocs.io/en/master/api.html#discord.Guild "discord.Guild").

This requires [`Intents.members`](https://discordpy.readthedocs.io/en/master/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
sly hamlet
# maiden fable sure

When I put that in though I keep on getting channels not defined how would I define it in this case?

maiden fable
#

interaction.channel

sly hamlet
#

oooooo ok thx

latent ember
maiden fable
#

Wym

boreal ravine
#

Someone give me a bot idea catpray

latent ember
dull terrace
#
if player.guild not in guild_gen_rank:
    guild_gen_rank[player.guild] = {player.id: player.generated} 
else:
    temp_ggr = list(guild_gen_rank[player.guild].items())
    for count, tup in enumerate(temp_ggr):
        _, generated = tup
        if player.generated > generated:
            temp_ggr.insert(count, (player.id, player.generated))
            guild_gen_rank[player.guild] = dict(temp_ggr[:5])
            break```

there has gotta be a better way to do this ![ass_think](https://cdn.discordapp.com/emojis/958740248697921637.webp?size=128 "ass_think") - updating top 5 scoring by generated
slate swan
latent ember
maiden fable
boreal ravine
# dull terrace ```python if player.guild not in guild_gen_rank: guild_gen_rank[player.guild...

yep, you forgot to format it ```py
if player . guild not in guild_gen_rank :
guild_gen_rank [ player . guild]= {player . id : player . generated } ;

     else  :
 temp_ggr= list( guild_gen_rank[ player.guild  ]  . items  (  ))  ;
 
 for ( count , tup  )  in enumerate( temp_ggr):

(_,generated ) =tup ;
if player . generated >generated :
temp_ggr. insert ( count, ( player . id , player. generated ) ) ;
guild_gen_rank [player .guild] =dict (temp_ggr [ : <ast.Constant object at 0x7f13465d77c0>: ] ) ;
break;

maiden fable
#

stop with pep 9001

latent ember
boreal ravine
slate swan
#

how to fix this

hot cobalt
#

@slate swan This channel is for Python discord bots

#

You'd want to ask in an off-topic channel, or find a JS server

slate swan
hot cobalt
#

I don't know what's popular, I don't use JS

#

!guilds there's probably some in the list

unkempt canyonBOT
#

Communities

The communities page on our website contains a number of communities we have partnered with as well as a curated list of other communities relating to programming and technology.

latent ember
#

How to make my discord bot be online 24/7

#

With python

placid skiff
#

VPS

latent ember
spice adder
#

I'm not quite sure what I'm doing wrong, but I can't get any commands to actually run

import discord
from discord.ext import commands
import os
from keep_alive import keep_alive

client = discord.Client()
Bot = commands.Bot(command_prefix="$")

@Bot.command()
async def repeat(ctx, arg):
    await ctx.send(arg)

keep_alive()
client.run(os.environ['TOKEN'])
``` No response or any error
latent ember
#

Wierd

placid skiff
placid skiff
spice adder
#

no monies

placid skiff
#

so?...

spice adder
#

Better way to do it?

placid skiff
#

to do what? your bot stays online untill you close up your terminal

spice adder
#

Isn't that only when self-hosted?

placid skiff
#

Lol ok you are using free hosting

spice adder
#

Correct

#

Now, am I doing something wrong with the command stuff itself?

placid skiff
#

Replit

While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:

  • The machines are super underpowered.

    • This means your bot will lag a lot as it gets bigger.
  • You need to run a webserver alongside your bot to prevent it from being shut off.

    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.

    • This means any file you saved via your bot will be overwritten when you next launch.
  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Heroku

  • Bots are not what the platform is designed for. Heroku is designed to provide web servers (like Django, Flask, etc). This is why they give you a domain name and open a port on their local emulator.

  • Heroku's environment is heavily containerized, making it significantly underpowered for a standard use case.

  • Heroku's environment is volatile. In order to handle the insane amount of users trying to use it for their own applications, Heroku will dispose your environment every time your application dies unless you pay.

  • Heroku has minimal system dependency control. If any of your Python requirements need C bindings (such as PyNaCl binding to libsodium, or lxml binding to libxml), they are unlikely to function properly, if at all, in a native environment. As such, you often need to resort to adding third-party buildpacks to facilitate otherwise normal CPython extension functionality. (This is the reason why voice doesn't work natively on heroku.)

  • Heroku only offers a limited amount of time on their free programme for your applications. If you exceed this limit, which you probably will, they'll shut down your application until your free credit resets.

placid skiff
spice adder
#

I see

#

Hm

#

When I try to look up how to self-host, I get a shit ton of links for "Host your bot 24/7 on our service for free!" So I'm not sure where to turn to learn how to self-host

placid skiff
#

nowhere, free hosting are bad, they're free because they provide a bad quality service and they get payed by the advertising and the visit on their site

#

you gain a bad service and they gain money, that's all

latent ember
#

How much hosting costs

spice adder
#

Trust me, I'd rather not be running on a free host either sadboii

placid skiff
latent ember
#

For how long

meager blaze
#

guys how you write message as in code bar?

placid skiff
#

it depends on the service you buy, to my customers I suggest a service which provides servers in Europe with a great discount for the first 6 months

spice adder
#

I was looking into a Vultr VPS

#

Would that be a good one to go with?

placid skiff
#

yup

slate swan
#

5 servers of 2 cores 4gb ram\

spice adder
#

Hmm

#

I'd honestly rather run off of my own PC's resources

hasty stump
#

can we merge 2 language bot in one ?
like python and java

maiden fable
spice adder
#

I usually leave my PC on 24/7, but the internet is definitely shitty here

#

I think I've got like 0.87 download and 0.49 upload

hasty stump
spice adder
#

Not sure

hasty stump
spice adder
#

I'm alright, thanks

hasty stump
#

i use that

slate swan
#

hey, i was wondering how can i do a if statement with something like:

with open("test.txt", "a") as test: if test does not exist:

#

but in the correct words.

#

then it proceeds to make it

slate swan
placid skiff
#

guess what? Github accepted me to the copilot technical preview

slate swan
slate swan
maiden fable
slate swan
#

also, is there a way to dm multiple members at once with code?

#

like i make a list, then dm each one of them

maiden fable
#

for loop and guild.members

slate swan
#

nono, not guild members i wanna specify the ids

maiden fable
#

!d discord.Client.get_user

unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
slate swan
#

with something like this:
list1 = ['firstid', 'secondid']

maiden fable
#

IDs are int
Use get_user

slate swan
#

i dont think you understand me

maiden fable
#

I do

slate swan
#

i wanna specify ids into a list, and then dm each one of them with a command

maiden fable
#
a = [1, 2, 3]
async def cmd(...):
    for user in a:
        await bot.get_user(user).send(...) 
slate swan
#

can i do it through a text file too?

upbeat gust
maiden fable
#

Sure

upbeat gust
slate swan
slate swan
upbeat gust
maiden fable
unkempt canyonBOT
#
Not likely.

No documentation found for the requested symbol.

upbeat gust
#

Reading files

maiden fable
#

What

#

!d open use this

unkempt canyonBOT
#

open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)```
Open *file* and return a corresponding [file object](https://docs.python.org/3/glossary.html#term-file-object). If the file cannot be opened, an [`OSError`](https://docs.python.org/3/library/exceptions.html#OSError "OSError") is raised. See [Reading and Writing Files](https://docs.python.org/3/tutorial/inputoutput.html#tut-files) for more examples of how to use this function.

*file* is a [path-like object](https://docs.python.org/3/glossary.html#term-path-like-object) giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed unless *closefd* is set to `False`.)
upbeat gust
#

with open(...) as f:

slate swan
#

cant i split the lines?

maiden fable
#

yes

upbeat gust
#

read it and then split

maiden fable
#

Instead use readlines()

upbeat gust
maiden fable
#

It will return a list tho

slate swan
#

dam i got no clue how to do it 😩

upbeat gust
upbeat gust
maiden fable
slate swan
#

with the list_of_ids and withopen in the code

maiden fable
#

It's a list

#

of ids

#

Use the for loop like I showed before

swift acorn
#
  def check(reaction, user):
    if str(reaction.emoji) == '✅' and reaction.message == msg1 and user == target:
      return True
    elif str(reaction.emoji) == '❌' and reaction.message == msg1 and user == target:
      return False

  try:
    await sotw.wait_for('reaction_add', check=check, timeout=60)
  except TimeoutError:
    await msg1.edit(f'Challange expired, {target_name} did not accept the challange in time.')
    return 0

1- How do I take a certain action if the user reacts with ❌

2- The timeout isn't working, after 60 seconds the reactions don't work, but it doesn't edit the message, to Challange expired message

maiden fable
swift acorn
#

so in the check I just check if it's the user and the msg1?

placid skiff
slate swan
bleak karma
#

what does this error mean?

HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In user_id: snowflake value should be less than or equal to 9223372036854775807.
placid skiff
#

code which raise the error?

upbeat gust
#

You have to loop through them

slate swan
bleak karma
# placid skiff code which raise the error?
@bot.command()
async def massban(ctx, members: Greedy[int], reason=None):
  if not members:
    await ctx.send("Please specify the users i need to ban.")
  else:
    list1 = members
    for i in list1:
      await ctx.guild.ban(discord.Object(id=int(i)))

    await ctx.send(f"successfully banned **{len(members)}** user(s).")
slate swan
bleak karma
upbeat gust
upbeat gust
#

The check should only check if the user is right and the emoji is in a list of acceptable ones

upbeat gust
placid skiff
upbeat gust
upbeat gust
swift acorn
placid skiff
#

probably the error is that he doesn't have the permission to ban one of the user

#

or the bot

#

or some some of those ints are not user id's

slate swan
#

learning multiple languages at once isnt the easiest

placid skiff
#

d.py is not suggested for beginners, you should know how OOP works and other python basic concept before get to it

slate swan
#
@bot.command()
async def cmd(ctx, test):
    with open("test.txt", "r") as f:
        a = f.read().splitlines()
        for user in a:
            await bot.get_user(user).send(f"{test}")  

would this work?
@upbeat gust

#

i wrote it on phone so the indenting might be a bit wrong

maiden fable
hasty bison
#

when i try mentioning a role it's like this

hot cobalt
#

At the very least I'd imagine you'd need to convert those to integers first, since I don't believe discord.py will accept an ID as a string

#

!d discord.Client.get_user

unkempt canyonBOT
#

get_user(id, /)```
Returns a user with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
hasty bison
#

iirc?

placid skiff
hot cobalt
#

Was it fetch for making a request instead?

placid skiff
#

yup

#

uhm i remember that there are some limitations for mentions in embeds

hot cobalt
#

I believe you can mention in embed content just fine, I don't think you can mention in titles though

slate swan
hot cobalt
#

Then you'd at the very least need to convert each ID to an int before passing it to get_user (which may also cause some issues like mentioned above)

slate swan
#

idk how...

placid skiff
#

probably to make a mention appear you should play with the type parameter of the embed, i researched this times ago but i do not fully remember how it works

#

yup

placid skiff
#

Sorry, attribute

upbeat gust
#

<@&id>

#

@hasty bison

latent ember
#

Anyone know good hosting service

upbeat gust
# latent ember Anyone know good hosting service

From dpy server:

Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
https://www.time4vps.eu/ Lithuania.
Self-hosting: Free hosting: Kinda free:
Any computer. No. Not even heroku. GCP, AWS have one year free micros.

Linode

Our mission is to accelerate innovation by making cloud computing simple, affordable, and accessible to all.

Vultr

Vultr Global Cloud Hosting - Brilliantly Fast SSD VPS Cloud Servers. 100% KVM Virtualization

misty stream
#

i am trying to get the streaming activity when someone goes live to say hey (member) is streaming

 @bot.event
    async def on_member_update(before, after, ctx):
        role = discord.utils.get(ctx.guild.roles, name="LiveLink")
        if role is None:
            await ctx.send('no one is streaming')
            return
        empty = True
        for guild in self.bot.guilds:
            for member in guild.members:
                if role in member.roles:
                    #await ctx.send("{0.name}".format(member))
                    #await ctx.send(member.activities[0].Activity_type)
                    if isinstance(member.activity, discord.ActivityType.streaming):
                        await ctx.send("he is streaming !")
                    else: 
                        await ctx.send("he not streaming")
                    empty = False
        if empty:
            await ctx.send("Nobody has the role")
#

⏫ yes what he says !

latent ember
#
from discord.ext import commands

client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    print('Bot is ready.')

@client.event
async def on_member_join(member):
    channel = client.get_channel(959102280731361302)
    embed=discord.Embed(title="Welcome!",description=f"{member.mention} Just Joined")
    await channel.send(embed=embed)

@client.event
async def on_member_remove(member):
    print(f'{member} has left an server.')

@client.command()
async def ping(ctx):
    await ctx.send(f'ping is '+str(round(client.latency * 1000))+'ms')```
#

What you mean?

misty stream
#

2x on member join Xd

latent ember
#

Oh yeah

#

Damn i made that midnight

#

Will fix it

hasty stump
#

can we merge 2 language bot in one ?
like python and java

slate swan
junior verge
#
@commands.command(name="mute", description="Mutes a user")
    @commands.has_permission(manage_messages=True)
    async def mute(self, ctx, user, time, reason):
        role = discord.utils.get(ctx.guild.roles, name="Muted") # retrieves muted role returns none if there isn't 
        if not role: # checks if there is muted role
            try: # creates muted role 
                muted = await ctx.guild.create_role(name="Muted", reason="To use for muting")
                for channel in ctx.guild.channels: # removes permission to view and send in the channels 
                    await channel.set_permissions(muted, send_messages=False,
                                                read_message_history=False,
                                                read_messages=False)
            except discord.Forbidden:
                return await ctx.send("I have no permissions to make a muted role") # self-explainatory
            await user.add_roles(muted) # adds newly created muted role
            await ctx.send(f"{user.mention} Has been muted for {reason}")
        else:
            await user.add_roles(role) # adds already existing muted role
            await ctx.send(f"{user.mention} Has been muted for {reason}")
            await asyncio.sleep(time)
``` How do I make it like if asyncio.sleep is done it will remove the muted role?
hasty stump
hasty stump
#

i wanted mean js sorry

#

java script and python

#

so there is no way?

slate swan
#

you shouldnt host the bot from two different tokens though

latent ember
#

How to make an command need a role

slate swan
unkempt canyonBOT
#

@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

If the message is invoked in a private message context then the check will return `False`.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").

Changed in version 1.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.MissingRole "discord.ext.commands.MissingRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/master/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
slate swan
#

add this deco above your command function

hasty stump
#

oh so if i code a bot with js and other one in python and if i launch both , it will merge ?

odd prawn
#

No, they will be two separate entities.

misty stream
#

i am trying to get the streaming activity when someone goes live to say hey (member) is streaming

 @bot.event
    async def on_member_update(before, after, ctx):
        role = discord.utils.get(ctx.guild.roles, name="LiveLink")
        if role is None:
            await ctx.send('no one is streaming')
            return
        empty = True
        for guild in self.bot.guilds:
            for member in guild.members:
                if role in member.roles:
                    #await ctx.send("{0.name}".format(member))
                    #await ctx.send(member.activities[0].Activity_type)
                    if isinstance(member.activity, discord.ActivityType.streaming):
                        await ctx.send("he is streaming !")
                    else: 
                        await ctx.send("he not streaming")
                    empty = False
        if empty:
            await ctx.send("Nobody has the role")

i need help with to send a message whenever a member has an activity type of streaming

junior verge
#

What does this mean?

misty stream
#

is there any1 who knwos how to ?

hasty stump
buoyant zodiac
junior verge
buoyant zodiac
#

it's an s

#

permissions ≠ permission

junior verge
#

Oh

#

My bad sorry

buoyant zodiac
#

Your fine

slate swan
latent ember
misty stream
slate swan
#

lmao

misty stream
#

so when they start streaming the bot says hey he is streaming

upbeat gust
hasty stump
misty stream
rocky hornet
#

when should i initialize my db?

#

what method should i override for that?

upbeat gust
#

Not member

misty stream
#

not discord streaming
twitch streaming

upbeat gust
junior verge
#

!paste

slate swan
junior verge
slate swan
#

forks* my autorrect sucks

rocky hornet
#

wat?

upbeat gust
rocky hornet
misty stream
upbeat gust
rocky hornet
#

whats that

crimson compass
#

what is the playing game code?

odd prawn
# hasty stump if same token as he said?

Using the same token to authenticate yourself for the API does not stop your two applications from being separate.
The only similarity is that they're operating using the same API entrypoint.

rocky hornet
upbeat gust
junior verge
misty stream
rocky hornet
#

is there anyone with coding experience?

upbeat gust
latent ember
#
@client.command()
@commands.has_permissions(ban_members = True)
async def ban(ctx, member : discord.Member, *, reason = None):
    await member.ban(reason = reason)```
upbeat gust
slate swan
upbeat gust
misty stream
upbeat gust
#

so setup_hook

latent ember
#

How should i do it?

#

My first bot

rocky hornet
#

wtf is setup_hook

junior verge
#

role needs to be higher then everyone

latent ember
#

Whats the command for banning someone?

upbeat gust
upbeat gust
junior verge
# latent ember Whats the command for banning someone?
@commands.command(name="ban", description="Bans a user")
    @commands.has_permissions(ban_members=True)
    async def ban(self, ctx, member: discord.Member = None, *, reason=None):
        if member == None:
            await ctx.send("Please mention a user") 
        else:
            await ctx.guild.ban(user=member, reason=reason)
            
            channel = self.client.get_channel(954837357239091260)
            embed = discord.Embed(title=f"{ctx.author.name} banned: {member.name}", description=reason)
            await channel.send(embed=embed)
            await ctx.send(f'Banned **{member.name}** for **{reason}**')
rocky hornet
#

it doesnt make sense for me to init db AFTER bot is ready

#

when bot is ready it means that its ready to operate so it needs db

latent ember
#

@junior verge can you help me in dms?

junior verge
#

Sure

upbeat gust
rocky hornet
#

im not even sure what setup_hook is

pliant gulch
#

on_connect is the gateway equivalent for READY. Discord.py's on_ready is just an event making sure the cache is populated

rocky hornet
#

i guess ill do it in between login and connect

pliant gulch
rocky hornet
#

andy seems competent

junior verge
#

Is it possible to like put a created role higher then @/everyone, if so how?

crimson compass
#

whats the command for playing game?

pliant gulch
rocky hornet
#

why do you need populated cache to connect db

junior verge
#

How do I fix this?

pliant gulch
#

In some cases some people might use it when starting the database

rocky hornet
#

ah

pliant gulch
#

But that's not the main issue, the main issue is being called more than once

rocky hornet
#
await super().login(...)
async with aiosqlite.connect(...):
    await super().connect()
#

is this fine?

junior verge
odd prawn
crimson compass
#

how do i make my bot send a custom emoji?

junior verge
#
self.client.add_roles
``` like that?
rocky hornet
#

lol

junior verge
#

im confused

hasty bison
#

how do i put custom emoji in bot's activity status?

odd prawn
# junior verge So how do I fix that?

You would need to translate the user parameter to a Member object.

So, for example, you could type-hint that to discord.Member.

>>> @commands.command()
>>> async def my_command(ctx, arg1: int, arg2: discord.Role):
>>>  print(type(arg1))

<class 'int'>```

This is because, when you pass command arguments into their functions, they are passed in by default as strings.

Edit: accidentally +1'd
maiden fable
#

U can't set a status for yr bot

#

Only activities like playing and stuff

junior verge
odd prawn
junior verge
#

Discord is imported yes

#

also, Is it possible to like put a created role higher then @/everyone, if so how?

upbeat gust
junior verge
#

What does this mean?

odd prawn
junior verge
#

Uhm

#

How do I fix that erm

#

@odd prawn

#
def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}

    unit = time[-1]

    if unit not in pos:
        return -1
    try: 
        val = int(time[:-1])
    except:
        return -2 
    
    return val * time_dict[unit]

class Moderation(commands.Cog):
    def __init__(self, client):
        self.client = client
    
    @commands.Cog.listener()
    async def on_ready(self):
        print(f"{self.__class__.__name__} Cog has been loaded\n-----")
    

    @commands.command(name="mute", description="Mutes a user")
    @commands.has_permissions(manage_messages=True)
    async def mute(self, ctx, user: discord.Member, time, reason):
        role = discord.utils.get(ctx.guild.roles, name="Muted") # retrieves muted role returns none if there isn't 
        if not role: # checks if there is muted role
            try: # creates muted role 
                muted = await ctx.guild.create_role(name="Muted", reason="To use for muting")
                await ctx.send("Make sure to put the role higher then `@everyone` or your default member role!")
                for channel in ctx.guild.channels: # removes permission to view and send in the channels 
                    await channel.set_permissions(muted, send_messages=False,
                                                read_message_history=False,
                                                read_messages=False)
            except discord.Forbidden:
                return await ctx.send("I have no permissions to make a muted role") # self-explainatory
            await user.add_roles(muted) # adds newly created muted role
            await ctx.send(f"{user.mention} Has been muted for {reason} for {time}")
            await asyncio.sleep(time)
            await user.remove_roles(role)
        else:
            await user.add_roles(role) # adds already existing muted role
            await ctx.send(f"{user.mention} Has been muted for {reason} for {time}")
            await asyncio.sleep(time)
            await user.remove_roles(role)
odd prawn
#

delay does not exist in that code block.

swift acorn
junior verge
odd prawn
#

I don't know what delay is.

junior verge
#

I don't see a delay

#

There is no delay in my code?

odd prawn
#

yeah there was something I was missing

#

time is a string, and not an integer.

junior verge
#

How do I make it an integer?

#
def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}

    unit = time[-1]

    if unit not in pos:
        return -1
    try: 
        val = int(time[:-1])
    except:
        return -2 
    
    return val * time_dict[unit]
``` here right
upbeat gust
#

I'm not sure about the order so check docs

junior verge
#
async def mute(self, ctx, user: discord.Member, time: int, reason):
``` like that or?
odd prawn
#

Type-hinting a function parameter that has the commands.command decorator will automagically change the type of the object passed as that parameter into the type of object being hinted at.

junior verge
#

But I do .mute @slate swan 1h test for example

crimson compass
#

how do i send custom emoji

junior verge
#

1h isn't a integer?, right?

junior verge
odd prawn
#

You see
This is why I shouldn't do things like this at 5:50am.

junior verge
#

Uhm

#

Can you still help me?

#

@odd prawn

maiden fable
#

U r doing int("1m") instead of int("1")

junior verge
#

Yeah I know

#

I don't want to do just 1

maiden fable
#

u can do time[:-1]

odd prawn
#

oh
wait

you never actually call the convert function

junior verge
#

oh

#

I want the convert function with 1h 1d 1m etc

#

1h

#

So what do I do? erm

misty stream
junior verge
#

@maiden fable Can you help me?

odd prawn
#

I mean, you made the function.
At this point, you would call it and pass in your time variable.

junior verge
#

Didn't I though?

odd prawn
#

No, you did not.

. . .
            await ctx.send(f"{user.mention} Has been muted for {reason} for {time}")
            await asyncio.sleep(time) # here
            await user.remove_roles(role)
. . .
junior verge
#

How do I then?

crimson compass
#
TypeError: Client.event() missing 1 required positional argument: 'coro'
junior verge
odd prawn
odd prawn
upbeat gust
#

let's say X is how many letters the main url is

junior verge
upbeat gust
#

And just do url[X:-1]

misty stream
#

so that removes 1 letter

upbeat gust
#

x skips the twitch url and -1 takes out the ending slash

misty stream
#

ooh wait Xd

#

cool thanks

upbeat gust
misty stream
#

so if i do 5 at the x it will remove 5 letters from the left

upbeat gust
#

Like lists, starts at 0

#

so just minus one from how many letters u wanna take away

#

wait

misty stream
#

ill wait Xd

junior verge
upbeat gust
#

no it starts from the first number and ends at the seconf

misty stream
#

the -1 removes 1 of the end can i make that 0 ?

#

cause i need the last letter Xd

junior verge
upbeat gust
junior verge
#

I did

junior verge
#
def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}

    unit = time[-1]

    if unit not in pos:
        return -1
    try: 
        val = int(time[:-1])
    except:
        return -2 
    
    return val * time_dict[unit]
upbeat gust
#

Or just don't put anything

junior verge
#
@commands.command(name="mute", description="Mutes a user")
    @commands.has_permissions(manage_messages=True)
    async def mute(self, ctx, user: discord.Member, time, reason):
        role = discord.utils.get(ctx.guild.roles, name="Muted") # retrieves muted role returns none if there isn't 
        if not role: # checks if there is muted role
            try: # creates muted role 
                muted = await ctx.guild.create_role(name="Muted", reason="To use for muting")
                await ctx.send("Make sure to put the role higher then `@everyone` or your default member role!")
                for channel in ctx.guild.channels: # removes permission to view and send in the channels 
                    await channel.set_permissions(muted, send_messages=False,
                                                read_message_history=False,
                                                read_messages=False)
            except discord.Forbidden:
                return await ctx.send("I have no permissions to make a muted role") # self-explainatory
            await user.add_roles(muted) # adds newly created muted role
            await ctx.send(f"{user.mention} Has been muted for {reason} for {time}")
            await asyncio.sleep(time)
            await user.remove_roles(role)
        else:
            await user.add_roles(role) # adds already existing muted role
            await ctx.send(f"{user.mention} Has been muted for {reason} for {time}")
            await asyncio.sleep(time)
            await user.remove_roles(role)
``` So how do I fix it?
misty stream
upbeat gust
misty stream
junior verge
#

Anyone else that can help?

upbeat gust
junior verge
#

Well if I don't get it maybe you could help would be nice..

upbeat gust
junior verge
#

I get that

upbeat gust
#

so convert the text to numbers (int)

upbeat gust
junior verge
upbeat gust
#

show the code where ur using <=

#

i cant find in te stuff u sent

junior verge
#

It's not in my code

slate swan
#

Just do int(delay) before doing >=.

junior verge
#

But where?

#

and also there no delay

upbeat gust
junior verge
#

And there is no >=

upbeat gust
slate swan
upbeat gust
#

from the arg u passed to asyncio.sleep

boreal ravine
upbeat gust
upbeat gust
junior verge
#

I just don't know what to do now

boreal ravine
upbeat gust
pliant gulch
upbeat gust
junior verge
pliant gulch
#

The regex for this is simple anyways, it's just (\d+) iirc

upbeat gust
#

didnt u make a function to convert it into seconds

junior verge
#

I did

upbeat gust
#

why arent you using that

junior verge
#

That's what I am asking

upbeat gust
junior verge
#

Go 1 message up from me..

upbeat gust
#

youre not using it

junior verge
#

I want to

#

But don't get how I can

slate swan
#

._.

junior verge
#

That's the whole point,.

upbeat gust
slate swan
#

convert(time)

upbeat gust
junior verge
upbeat gust
#

idk man maybe between where ur getting it and where u need the result

slate swan
upbeat gust
pliant gulch
#

It would be probably a good idea to cast float instead of int

#

!e ```py
float("123.123")
float("123")
int("123.123")

unkempt canyonBOT
#

@pliant gulch :x: Your eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 3, in <module>
003 | ValueError: invalid literal for int() with base 10: '123.123'
pliant gulch
#

That is, if you think you ever need to work with floating point numbers

slate swan
#

hi, i didnt know whereto ask this question but im going to shoot it here

slate swan
#

oh ok then maybe not here

#

whereelse can i ask a person and not a bot

slate swan
upbeat gust
slate swan
#

i didn't know

upbeat gust
slate swan
#

i dont use dicod and it is really confusing

upbeat gust
#

alright

slate swan
#

why am i getting this error?
'NoneType' object has no attribute 'send'

@bot.command()
async def changelog(ctx, test):
    with open("/root/Textfiles/owner.txt", "r") as f:
        a = f.read()
        if str(ctx.author.id) in a:
            with open("/root/Textfiles/changelog_ids.txt", "r") as f:
                a = f.read().splitlines()
                for user in a:
                    await bot.get_user(user).send(f"{test}")
#

how can i fix it?

pliant gulch
#

Was?

#

That makes no sense still kek

#

If the cache was populated there would be users in there

#

You should just do get_user(...) or await fetch_user(...)

supple crescent
#

how can i make it so any message typed in a channel is deleted?

#

thanks

slate swan
pliant gulch
#

No

#

You want to grab from cache first, if it returns None use fetch_user

slate swan
#

what even is cache

pliant gulch
#

In discord.py's case, the cache is an in-memory mapping

#

This is almost always a key-pair consisting of the snowflake, to the library model

boreal ravine
slate swan
#

what if i do this instead?

for user in a:
    await bot.send(user, f"{test}")
twin flower
#

My balance command won't work, apparently the bot isn't recognizing that the command is there.

#

Have no clue why.

slate swan
#

doesnt fetch fetch the id?

twin flower
#

No the console is clear but the error catcher detects something

upbeat gust
#

since like version 1

slate swan
#

oh

twin flower
# upbeat gust CommandNotFound? show code

here's the code

# Imports
import discord
from discord.ext import commands
from random import randrange
import aiosqlite
import asyncio
import time

# Def main func
async def checkBal(self, ctx, user : discord.Member):
    db = await aiosqlite.connect('ArchDornanDatabase.db')
    cursor = await db.cursor()
    await cursor.execute(f"SELECT * FROM MainTable WHERE UserID = {user.id}, GuildID = {ctx.guild.id}")
    result = await cursor.fetchone()
    if result:
      return
    if not result:
      await cursor.execute(f"INSERT INTO MainTable(GuildID, UserID, Wallet, Warns), VALUES(?,?,?,?)", (ctx.guild.id, user.Id, 0, 0))
    await db.commit()
    await cursor.close()
    await db.close()


# Def main class
class Bal(commands.Cog):
  @commands.command
  async def bal(self, ctx, user : discord.Member=None):
    if user is None:
      user = ctx.author

    await checkBal(self=self, ctx=ctx, user=user)
    db = await aiosqlite.connect('ArchDornanDatabase.db')
    cursor = await db.cursor()
    await cursor.execute(f"SELECT * FROM MainTable WHERE UserID = {ctx.author.id}, GuildID = {ctx.guild.id}")
    embed=discord.Embed(title="**Wallet Balance**", description=f"{user} has {result[2]} coins in their wallet!", color=0xffffff)
    await ctx.send(embed=embed)
      
# Initialize
def setup(bot):
    bot.add_cog(Bal(bot))
    print('Bal is loaded')
upbeat gust
twin flower
upbeat gust
#

forgot the ()

twin flower
#

oh yeah

upbeat gust
#

lmao

twin flower
#

whoops

spring flax
#

you connect to a DB when overriding start method right? not the run method or connect

twin flower
#

it works except for a syntax error

pliant gulch
#

There are other ways as well

twin flower
#

im tryna figure out how to check multiple things on this line but its just syntax erroring

spring flax
pliant gulch
#

nothing ?

#

It just connects

#

Although run isn’t a coroutine function

#

So you can’t make your connection easier if it’s async

junior verge
#

Is it possible to like put a created role higher then @/everyone, if so how?

#

Move a role up 1 place

spring flax
#

okay, so it should be done in start but all three can work?