#discord-bots

1 messages · Page 1056 of 1

slate swan
#

if nokia can have it then every keyboard can

formal basin
#
 @tasks.loop(seconds=30)
async def checkforvideos():
  with open("youtubedata.json", "r") as f:
    data=json.load(f)
  
  
  print("Now Checking!")

  for youtube_channel in data:
    print(f"Now Checking For {data[youtube_channel]['channel_name']}")
    
    channel = f"https://www.youtube.com/channel/{youtube_channel}
    html = requests.get(channel+"/videos").text

    
    try:
      latest_video_url = "https://www.youtube.com/watch?v=" + re.search('(?<="videoId":").*?(?=")', html).group()
    except:
      continue

    if not str(data[youtube_channel]["latest_video_url"]) == latest_video_url:

     
      data[str(youtube_channel)]['latest_video_url'] = latest_video_url

      with open("youtubedata.json", "w") as f:
        json.dump(data, f)

 
      discord_channel_id = data[str(youtube_channel)]['notifying_discord_channel']
      discord_channel_id = client.get_channel(int(discord_channel_id))

     
      msg = f"<@&976169188274086019> {data[str(youtube_channel)]['channel_name']} Just Uploaded A Video Or He is Live Go Check It Out: {latest_video_url}"

      await discord_channel_id.send(msg)

checkforvideos.start()


@checkforvideos.before_loop
async def checkforvideos():
  print('waiting... 2 ')
  await client.wait_until_ready()


@slash.slash(name="add_youtube_notification", description="admin only")
@commands.has_permissions(manage_roles=True)
async def add_youtube_notification(ctx, channel_id: str, *, channel_name: str):
  with open("youtubedata.json", "r") as f:
    data = json.load(f)
  
  data[str(channel_id)]={}
  data[str(channel_id)]["channel_name"]=channel_name
  data[str(channel_id)]["latest_video_url"]="none"

  #you can also get discord_channe id from the command 
  #but if the channel is same then you can also do directly
  data[str(channel_id)]["notifying_discord_channel"]="975360118591991818"

  with open("youtubedata.json", "w") as f:
    json.dump(data, f)

  await ctx.send("Added Your Account Data!") ```
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.

slate swan
#

!code

unkempt canyonBOT
#

Here's how to format Python code on Discord:

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

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

slate swan
#

man ;-; discord_slash

formal basin
slate swan
#

sarcastic....?

slate swan
slate swan
slate swan
#

while loading i get this error

warped mirage
#

Does it also include level system ye?

slate swan
#

In discord 2.0 it's a coro

warped mirage
#

@slate swan yo indents fixed .

slate swan
#

?

warped mirage
#

I fixed my indents lol

slate swan
warped mirage
#

I still need help tho

slate swan
#

?

#

what?

slate swan
shrewd apex
warped mirage
slate swan
slate swan
#

lol

slate swan
warped mirage
#

I have quite alot idk how to fix

slate swan
#

Can u show

#

Writing code again is fun

warped mirage
#

Ok lemme show current code

slate swan
#

Alr

warped mirage
#

For the event .

shrewd apex
# warped mirage Ok lemme show current code

time stamps:
0:00 - intro
0:20 - discord bot setup
0:56 - online database setup
2:08 - project set up
3:40 - say hi to arc
3:50 - continue setup
4:56 - increasing XP
7:49 - rank command
9:55 - leaderboard
10:52 - adding cogs
11:05 - final product
11:15 - outro
———————
Thanks (for non copyright music):
----------------------------...

▶ Play video
slate swan
shrewd apex
#

just get the concept

slate swan
#

Yt tutorials are trash

slate swan
shrewd apex
#

never said to copy

warped mirage
scarlet snow
shrewd apex
slate swan
#

🗑 (yt tutorials)

#

!pip discordsuperutils

unkempt canyonBOT
slate swan
#

😔

shrewd apex
#

and basically level system is just an ap or gp formula however u want it

crimson compass
#

how do i make a warning system

shrewd apex
#

copy that

slate swan
warped mirage
slate swan
#

Ok

#

or terminal

#

Can u show ss

slate swan
slate swan
slate swan
warped mirage
slate swan
scarlet snow
#

just store in a db

crimson compass
#

and if sb has like 4 warnings he gets banned

slate swan
#

i do have v2.0

shrewd apex
#

store in a db and if warncount == 4 then ban

scarlet snow
#

yup

slate swan
crimson compass
#

yes

slate swan
#

I would suggest adding a boolean column that checks if the user is already banned or not

#

if not xp or not lvl
tf?

shrewd apex
slate swan
crimson compass
slate swan
#

json shouldnt be used in this case

slate swan
scarlet snow
#

don't touch json for that

slate swan
#

use sqlite, postgresql, or mysql (recommended)

#

you cant complain sparky

crimson compass
slate swan
#

Db

shrewd apex
#

its fine for a small case warn system and a json here is not going to cause delays due to warn being rarely used and its only a one time use

slate swan
warped mirage
#

@slate swan best as i could

slate swan
paper sluice
crimson compass
#

ah

slate swan
warped mirage
#

cant fit all in

shrewd apex
#

enough for beginners

slate swan
#

they create a database

scarlet snow
slate swan
#

they interact with a database

shrewd apex
slate swan
#

what

paper sluice
slate swan
warped mirage
slate swan
slate swan
scarlet snow
warped mirage
slate swan
#

yes yes

paper sluice
#

dont name commands.Bot to client lemon_angrysad

slate swan
#

Imma go and play some cHess I'm out

scarlet snow
paper sluice
slate swan
#

god damn

scarlet snow
#
async def setup():
    await ....
#

thats dpy 2.0 i assume?

warped mirage
slate swan
#

Ye

scarlet snow
#

because it wasn't async ig

slate swan
slate swan
warped mirage
#

Just doesn’t respond to the level command

#

And event is fucked I think

slate swan
#

Lemee see

#

There's database that idk

#

Maybe that

warped mirage
slate swan
warped mirage
slate swan
#

um wait

#

halp

#

@tasks.loop()

slate swan
#

I havbe the @tasks.loop() function

#

but I want to run it multiple times in parrarel

#

what do u mean by parrarel

warped mirage
#

Oh wrong person

slate swan
#

Not for you

slate swan
#

they running and doing they thing

#

🤨

slate swan
shrewd apex
#

🥶

slate swan
slate swan
shrewd apex
#

tasks.loop() with that use before and after loop

slate swan
#

ping

shrewd apex
#

oof

slate swan
#

Nvmd

#

typing I ghostnpinged u by mistake

shrewd apex
slate swan
#

for a in arg:
func(a)

#

im trynna do ```py
@tasks.loop(seconds=10)
async def balls(arg):

do stuff w args

@client.command()
async def uwu():
balls.start(arg1)
balls.start(arg2)

#

it doesnt let me do this

#

holyp

warped mirage
#

@slate swan can u check mine or nah

shrewd apex
#
@tasks.loop(seconds=60)  # task runs every 60 seconds
async def my_background_task(self):
        #stuff
@my_background_task.before_loop
async def before_my_task(self):
       await self.wait_until_ready()
#

mistake

paper sluice
#

👍

slate swan
#

you could add it directly to do the task

#

and it wont be a problem whenever it is looping

#
    raise RuntimeError('Task is already launched and is not completed.')
RuntimeError: Task is already launched and is not completed.
#

Error says all

slate swan
#

this is whenI tried to launch the 2nd task\

slate swan
#

Didn’t know all the changes in new version

shrewd apex
slate swan
#

same task w/ diff args

slate swan
shrewd apex
slate swan
#

will have to create separate functions that do the same things

#

bruh

slate swan
#

its slike threading

warped mirage
slate swan
#

im trying to use discord tasks like how threads work

shrewd apex
#

or define the parameters in the task and call the function in the task

slate swan
#

but the ask here needs to in teract with the user

shrewd apex
#

before loop will run it the first time then the main task loop will run it the second time

heavy shard
#

@warped mirage let me guess... the xp won't go above 3 and it says user leveled to same level every user message?

dull terrace
#

bot launch is going well, 30 servers in 5 days and 23 votes froggy_chill

slate swan
#

Its hard to describe whats going on but it is checking every line for the mentioned user, and then saying no if the line doesnt contain the user... I dont know if i said that right...

How could i fix that?

dull terrace
#

free for a year froggy_chill

slate swan
#

Nice

maiden fable
#

Mine is like 1.5 years or smth old, 155 servers and hardly any votes lol

slate swan
#

Lol

maiden fable
#

No votes cz I don't really have anything locked behind a votewall lol

heavy shard
dull terrace
#

my other one had 800 servers in 6 months, so this is looking a lot better

maiden fable
slate swan
heavy shard
#

yep verification

slate swan
#

like

#

halp

maiden fable
#

Yes. U r full of anxiety when its submitted for verification. What if this happens, what if that happens, what if my bot switches off during verification, and so on

dull terrace
#

i think locking behind a votewall is fine for some things

maiden fable
dull terrace
#

get something for your work

maiden fable
slate swan
maiden fable
#

Read the FAQs

slate swan
#

Its full of buttons

maiden fable
#

Hm

#

I just tried to do smth different 🤷‍♂️

slate swan
#

I said hi

#

He said what do u like I started a different topic a replied and it send hmm interesting lol

dull terrace
#

that must be taking a ton of resources to host a chat bot no?

formal basin
#

ANYONE KNOW HOW I CAN MAKE A TIKTOK NOTIFIER THERE IS NO TUTORIALS ONLINE ANYONE KNOW?

dull terrace
#

i would limit usage time per person per day and put that behind a vote wall

slate swan
#

Disable caps

dull terrace
#

that way only the people who are really enjoying your bot will run into the votewall

#

and theyll be happy to vote anyway most of the time

slate swan
#

hm I need help too

#

😔

warped mirage
#

can someone recommend me a tut for level system

slate swan
#

like, running it using the event loop would be a good idea?

slate swan
supple thorn
#

What stuff

#

Opening a image?

slate swan
#

creating images to be specific

robust fulcrum
#

Can anyone help me how to use @unkempt canyon in our bot pls
Me dont know how to use dockerfile

slate swan
#

dockerfile isnt even related-

supple thorn
slate swan
dull terrace
#

7739monkathink i use pillow but haven't needed to make it run async

robust fulcrum
slate swan
robust fulcrum
#

Btw do anyone know about how can we make a slot command and a database to it

paper sluice
#

slot command? what does it do?

robust fulcrum
#

Hmm like Pokemon slot command

#

In mudea bot

dull terrace
#

what is a pokemon slot command

supple thorn
slate swan
paper sluice
robust fulcrum
#

Ye

dull terrace
#

what specifically are you stuck on while making it

robust fulcrum
#

Hmm idk how to make

dull terrace
#

have you coded in python before?

cloud dawn
warped mirage
#

Can someone help me make a levelling system lol

slate swan
#

yert quite helpful for this purpose

cloud dawn
slate swan
dull terrace
#

I still don't fully understand blocking and async code

#

would it block the function for everyone or just the person on that thread

cloud dawn
#

!blocking

unkempt canyonBOT
#

Why do we need asynchronous programming?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.

What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:

import discord

# Bunch of bot code

async def ping(ctx):
    await ctx.send("Pong!")

What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.

async libraries
The standard async library - asyncio
Asynchronous web requests - aiohttp
Talking to PostgreSQL asynchronously - asyncpg
MongoDB interactions asynchronously - motor
Check out this list for even more!

dull terrace
#

would the entire bot stop processing anything until the pillow image is done though

paper sluice
#

yes

dull terrace
#

if it's within an async function

cloud dawn
#

no

dull terrace
#

just for that thread right, the one person

potent spear
#

you can make it run in executor to have it run asynchronously

#

it's not because you put sync code in an async function that it'll run asynchronously

cloud dawn
#

If it's an async function the functions that you call inside that function are async.

potent spear
#

your options are the following: find an async wrapper of the lib you're using / run in executor to have a sync function run async

dull terrace
#

so for argument sake

warped mirage
#

@potent spear sup

#

lets continue .....

cloud dawn
#

The best practice however would be to make your own async pillow api.

robust fulcrum
potent spear
#

I'm quite busy today, just try to debug the commands one by one I'd say

robust fulcrum
dull terrace
#
async def on_message(message):
  a_non_async_function()```
this would block anyone else receiving a response when sending a message until the first a_non_async_function is done
#

or just block each person until it's done

sick birch
#

In general it blocks your entire bot

#

Particularly if it blocks heartbeats you’re going to get disconnected

dull terrace
robust fulcrum
#

Lol

slate swan
robust fulcrum
#

Hmm do anyone know a tutorial on making a slot command?

cloud dawn
#

It's like if you can't breathe and your heart can't beat at the same time xD

cloud dawn
robust fulcrum
paper sluice
dull terrace
#

i think when i tested my pillow image generation only takes 1/100th of a second or less

brisk linden
#

I’m terrible at python(

dull terrace
#

so shouldn't be a problem right

heavy shard
#

or when you drink a big bottle of water, you can't breathe until you finish

dull terrace
#

seeing as only 50 people can use the bot in a second for the discord api

plucky sundial
#

Yah

#

The only drawback

cloud dawn
plucky sundial
#

Of python discord api

robust fulcrum
warped mirage
#

guys

paper sluice
dull terrace
robust fulcrum
paper sluice
#

huh? weren't there three discord-bots related threads??

paper sluice
#

what happened to the third one?

cloud dawn
warped mirage
#

ImportError: cannot import name 'commands' from 'discord.ext' (unknown location) tf is happening

#

someone help me

cloud dawn
warped mirage
#

nope

slate swan
warped mirage
#

i downloaded nextcord , but then i deleted it

warped mirage
cloud dawn
#

I recommend using pip list and see what is installed.

warped mirage
#

ok

dull terrace
#

we need code

warped mirage
#

BRUh tf

#

i downloaded nextcord and now it affected all my bots in py

robust fulcrum
#

Should I start making with random?

warped mirage
#

but i deleted it

dull terrace
#

start making it and then when you get stuck come and we will help

robust fulcrum
#

Thank u ☺️

warped mirage
#

ok good i fixed it

robust fulcrum
#

@dull terrace

Slot = random.randint(1,2,3,4,5) 

Is it fine?

#

Will it work if i use it in command

dull terrace
#

random.randint takes two arguments

#

so it would be random.randint(1,5)

robust fulcrum
#

Hmm how can I put more arguments?

#

Oh k

#

Means it will choose random from numbers between 1 and 5

dull terrace
#

yes, including 1 and 5

robust fulcrum
#

Ok

warped mirage
#

!discord-py

#

damn

paper sluice
#

pithink what are you trying to do?

robust fulcrum
#

@dull terrace

@client.command()
async def pokemonslot(ctx):
     slot = random.randint(1,10)
        if slot == 1:
                await ctx.send("wow you won a uncommon charizard!")

This?

paper sluice
#

u need to take ctx as an arg for ur function
and u dont need to indent that if

robust fulcrum
#

Oh i forgot

dull terrace
#

indentations should be four spaces, you indent at the start of a function, the line after an if, for or while

slate swan
#

How do I use on_message in cog?

dull terrace
robust fulcrum
#

Like how many Pokemon a user have won

dull terrace
#

good set of tutorials on databases

slate swan
slate swan
unkempt canyonBOT
#

classmethod listener(name=...)```
A decorator that marks a function as a listener.

This is the cog equivalent of [`Bot.listen()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.listen "discord.ext.commands.Bot.listen").
robust fulcrum
#

Me not understanding about it

thorny scarab
#

how can I add reactions to a message and start a thread just by message id rather than the obj? (using disnake)

robust fulcrum
#

How can we make that bot wait for 2 seconds and send message

slate swan
#

unresponsive

#

oh wat

#

wait*

#

fixed it sorry for ping

#

Huh

#

how do i check if a message is having . . . in it?

#

not in start or end

slender finch
#

can anyone help me with bot development on discord using python?

slate swan
unkempt canyonBOT
#

coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.

If *result* is provided, it is returned to the caller when the coroutine completes.

`sleep()` always suspends the current task, allowing other tasks to run.

Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.

Deprecated since version 3.8, removed in version 3.10: The `loop` parameter. This function has been implicitly getting the current running loop since 3.7. See [What’s New in 3.10’s Removed section](https://docs.python.org/3/whatsnew/3.10.html#whatsnew310-removed) for more information.

Example of coroutine displaying the current date every second for 5 seconds:
slender finch
# slate swan yes?

thanks! well, i need to know the framework required and a step by step process :) just need some guidance from someone experienced... i need to make it as a project...

slate swan
#

it shows a tutorial with nextcord and disnake

#

how to flatten in d.py v2.0?

slate swan
slate swan
#

nvm

#

and that link is a redirect

#

i know its tutorial.vco...

#

should use the actual link as vco said it wasnt going to be a redirect for too long

#

i know 😔

#

🥰

slate swan
sick birch
slate swan
#

flatten users in a reaction

sick birch
#

It’s already a list isn’t it?

#

Oh just checked the docs

#

You can call .flatten() on it like usual

slate swan
#

What does flatten do

sick birch
#

It converts an AsyncIterator to a regular list

slate swan
#

Oh

#

whats your issue?

#

just write it here

#

wheres your assets/css destination?

#

looks like you dont habve one

#

you dont have the folders assets and css

#

you gotta create an assets folder and in that folder a css folder and in the css folder a styles.css

#

how do I use dpy and change my bot's description using its token

slate swan
slender finch
slate swan
#

@slate swan wrong channel

#

claim a help channel

#

Don't ask for help to topics that are not in the channel's description

slate swan
# slate swan any doc or help?

you dont flatten in 2.0 ```py

before

users = await reaction.users().flatten()

after

users = [user async for user in reaction.users()]

#

the iteration below #after does the same thing as flatten in 2.0

slate swan
#

for that, mins need to be an integer/float so typehint to int

warped mirage
#

guys can someone help me fix my levelling system

slate swan
#

what issue do you face ?

quaint epoch
#

you probably didn't type hint/convert it

warped mirage
tropic burrow
#

why doesn't this deposit function work


@client.command()
@commands.cooldown(1,5,commands.BucketType.user)
async def deposit(ctx, amount):
  memberData = loadmemberdata(ctx.author.id)
  if memberData.wallet < amount:
    errorembed = discord.Embed(
      title="LOL POOR BOZO",
      description=f"DUDE YOU CANT DEPOSIT {amount} WHEN YOU ONLY HAVE {memberData.wallet}"
    )  
    await ctx.channel.send(embed=errorembed)
  else:
    memberData.wallet -= amount
    memberData.bank += amount
    mbed = discord.Embed(
    title="Monkebux deposited..",
    description=f"You deposited {amount} monkebux into the bank"
    )
    await ctx.channel.send(embed=mbed)
#

no errors, just thaat the wallet and bank dont get affected at all

#

and the bot sends nothing

slate swan
#

because you dont change anything!

tropic burrow
#

i said memberdata.bank += amount

#

read the code

slate swan
#

My bad

honest laurel
tropic burrow
#

oh ye i forgor to call savememberdata

#

im dumb

slate swan
#

¯_(ツ)_/¯

tropic burrow
#

i saved it

slate swan
#

what's memberData

tropic burrow
#
 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.command()
@commands.cooldown(1,5,commands.BucketType.user)
async def deposit(ctx, amount):
  memberData = loadmemberdata(ctx.author.id)
  if memberData.wallet < amount:
    errorembed = discord.Embed(
      title="LOL POOR BOZO",
      description=f"DUDE YOU CANT DEPOSIT {amount} WHEN YOU ONLY HAVE {memberData.wallet}"
    )  
    await ctx.channel.send(embed=errorembed)
  else:
    memberData.wallet -= amount
    memberData.bank += amount
    mbed = discord.Embed(
    title="Monkebux deposited..",
    description=f"You deposited {amount} monkebux into the bank"
    )
    await ctx.channel.send(embed=mbed)
    savememberdata(ctx.author.id, memberData)
#

also i did import

#

discord and stuff

slate swan
#

Does @lament depot have ludo or something related to dice 🤨

tropic burrow
#

i just did not include it

slate swan
#

im surprised how are you using an int as a pickle dictionary key.

tropic burrow
#

yeah im kinda new to pickle

slate swan
#

well, using an actual database is a better option.

tropic burrow
#

idk how to do that

warped mirage
#

can someone help me fix my leveling system or give me a code

slate swan
slate swan
slate swan
#

got this error ^

#

reaction is None

warped mirage
#

can someone help me lol

#

oh nbm

slate swan
#

On the embed I sent

#

you cant mention a list comp anyways....

slate swan
slate swan
#

If yes then how?

slate swan
sick birch
#

Probably a list comp or map

slate swan
warped mirage
#

guys i need help

paper sluice
#

With?

warped mirage
#

my level system command is not working , and for the event it does this

#

and does that every message i do

minor oriole
#

Do we have any discord server for C too?

paper sluice
heavy shard
heavy shard
empty kernel
#

I created a basic welcome bot for a friend's server, which sends an Embed to new members, but I'm seeing inconsistent results. It always sends a message, but I'm using member.mention and that mention can be any of the following:

  1. Username (this is what I want)
  2. Userid (not desirable, it's just a long number)
  3. invalid-user (this one only seems to show up on my phone, but also undesirable)
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv


load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.members = True

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

@bot.event
async def on_member_join(member):
    general_channel = None
    guild_joined = member.guild
    general_channel = discord.utils.get(guild_joined.channels, name='general')

    if general_channel:
        embed=discord.Embed(title="Welcome!",description=f"Welcome {member.mention}!!")
        await general_channel.send(embed=embed)

bot.run(TOKEN)

Is something wrong in my code? Am I running into some sort of caching issue where the username isn't available yet? Just curious if anyone has any thoughts as to what might be causing the inconsistent behavior?

neat shuttle
#

can u show ss of the error ?

#

also you should use the member.id to mention someone

empty kernel
#

There isn't an error. It "sends" just displays the mention incorrectly. I thought I needed to use mention in order to actually "mention" them? Meaning doing an @ at them instead of just printing the text of their name?

neat shuttle
#

that should work for u

empty kernel
#

so replace:

embed=discord.Embed(title="Welcome!",description=f"Welcome {member.mention}!!")

with

embed=discord.Embed(title="Welcome!",description=f"Welcome <@{member.id}>!!")
neat shuttle
#

yes try that

empty kernel
#

ok. Thanks! I'll give it a try!

flint isle
#
  bot = commands.Bot(command_prefix="$")
#

uhh tahts the first time ive had that error

#

yeah idk what its talking about.

neat shuttle
#

turn on the message intent and pass it into ur code

flint isle
#

the intent is enabled in the portal what is the code that i need ot insert?

warped mirage
tiny ibex
#

Hey can someone tell me what is the issue here

eru jsk py
import aiohttp
import disnake
from io import BytesIO

query = "janji+heroes+tonight+ncs"
url = f'https://some-cool-api.herokuapp.com//youtube_music?query={query}'
async with aiohttp.request("GET", url=url) as response:
    data = BytesIO(await response.read())
with open(f"./song.mp3", "wb") as f:
    f.write(data.getbuffer())

channel = _bot.get_channel(919885560863146008)
await channel.send(file = disnake.File("./song.mp3"))```
sick birch
#
  1. happens when your client hasn't cached that user, not a bug but a limitation. Nothing you can do about that either
#

Unfortunately, in your case, you have 2 options:

  1. Leave it as is, and deal with the inconsistent mentions
  2. Change it to something plaintext that will always work, like the user's name and discrim
empty kernel
#

oh! ok, I hadn't tried the suggestion above in production yet. Sounds like there's no real need to? As in all/both cases, it's a software or cache limitation

unkempt canyonBOT
#

discord/member.py lines 567 to 570

@property
def mention(self) -> str:
    """:class:`​str`​: Returns a string that allows you to mention the member."""
    return f'<@{self._user.id}>'```
sick birch
empty kernel
#

Gotcha. That's great to know! Especially as a beginner with discord.py knowing it's not something I'M doing wrong

#

Thanks again @sick birch !

sick birch
#

Yeah, it can be difficult to tell. Discord in general has a few quirks like this littered around.

sick birch
sick birch
tiny ibex
#

But the code works fine when run
This happens only when running from jsk

slate swan
#
@bot.command()
async def fetchall(ctx):
    guild = ctx.guild
    memberList = guild.members
    for member in list(ctx.guild.members):
        print(member)```
prints one member only which is the bot, why?
slate swan
#
Traceback (most recent call last):
  File "C:\Users\Harckepy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Harckepy\Desktop\shitty bot or smth\main.py", line 22, in on_message
    role = discord.utils.get(message.guild.roles, "Awaiting on first message")
TypeError: get() takes 1 positional argument but 2 were given
``` this some bs
#
@bot.event
async def on_message(message):
    role = discord.utils.get(message.guild.roles, "Awaiting on first message")
    if(role in message.author.roles):
        message.author.remove_roles(role)
    await bot.process_commands(message)
potent spear
slate swan
#

why javascript?

potent spear
potent spear
potent spear
slate swan
#

i tried it with that earlier and had the sama error

potent spear
#

!d discord.Guild.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID.

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

stackoverflow/yt tutorials mb

#

still...

#

how the answers on stackoverflow are so top-notch smh

sick birch
#

Look into subclassing HelpCommand

brave forge
#

If you do not understand what exactly I am writing, do not even try to say anything, do not provoke me to insults.
how can I make it so that only the mentioned user can click on the button ?

#
    async def interaction_check(self, interaction) -> bool:
        if interaction.user.mention == False:
            await interaction.response.send_message("Вы не можете ответить за друго-го участника", ephemeral= True)
            return False
        else:
            return True```
sick birch
#

The most common way is to pass it in as an argument

brave forge
#

Well, I did about the same nonsense

brave forge
sick birch
#

You need to compare the user who sent the interaction (e.g clicked the button) to the user who was mentioned. We can get the person who clicked the button using interaction.user, which you already seem to have. You just need to get the mentioned user in, by passing it in as arguments like I mentioned

blissful lagoon
brave forge
blissful lagoon
#

link you?

sick birch
#

For example:

class MyView(discord.ui.View):
  def __init__(self, member: discord.Member, ...):
    super().__init__(...) # instantiate a view like usual
    self.member = member 

  async def interaction_check(self, interaction: discord.Interaction):
    return self.member == interaction.user # You can do anything else here, since you have access to the `member` object

@bot.command()
async def my_command(ctx: commands.Context, ...):
  member: discord.Member = ... # this will be the only person who can click the button
  view = MyView(member)
  await ctx.send(view=view)
brave forge
flint isle
#

hrmm my file structure is

Folder:whiskeybot
bot.py
.env
⇾cogs
⇾⇾events.py

how can i refence the .env inside the events cog?

brave forge
blissful lagoon
#

!mute 419481276765175808 1d You need to take some time to stop and think about what I and other moderators have told you. You cannot engage with our community like this.

unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied mute to @brave forge until <t:1653244935:f> (23 hours and 59 minutes).

sick birch
flint isle
#

i am using dotenv

sick birch
#

You could pass it to your cog from within setup()

flint isle
#

will it call the .env that is a folder above?

sick birch
#

usually you only want to access your .env once, when your bot is initially starting

#

from there you can pass your data around

#

Are you using extensions?

flint isle
#

ell im also storing test guild ids there for slash commands and i need to ref them from there

flint isle
sick birch
#

You can bind the data to a bot instance

manic path
#

Awaiting this object: <bound method Bot.hidden_commands of <bot.bot.Bot object at 0x10ec42b90>> would probably not give me any result, I assume.
Will it?

sick birch
#

Then in setup, you can do like so:

class MyCog(commands.Cog):
  def __init__(self, bot: commands.Bot, ...):
    self.bot = bot
  
  @bot.command()
  async def some_command(self, ctx: commands.Bot, ...):
    guild_ids = self.bot.data
    # do something

def setup(bot: commands.Bot):
  bot.add_cog(MyCog(bot=bot))
#

2.0 makes setup async, but same concept

#

The important bit is that you bind your .env data as a bot var

manic path
flint isle
#

would that work through disnake?

sick birch
manic path
#

nothing

sick birch
sick birch
manic path
#
    async def hidden_commands(self):
        """
        Hides the commands which require `role_checks` check.
        `redirect_output` and `channel_checks` are exceptions.
        """
        commands_ = [command_ for command_ in self.commands if 'role_check' in 
                     [parent_check.__qualname__ for parent_check in command_.checks]]
        
        for cmd in commands_:
            print(cmd)
            cmd.hidden = False
sick birch
#

Then it should return None

manic path
#

print(cmd) was for debugging but it don't even do that when I run the bot

sick birch
#

Are you actually awaiting it?

potent spear
#

it's not even an async function

manic path
#

Pretty sure, I am.

    for func in bot_.helper_functions:
        print(func)
        await func()
potent spear
#

ah, there it is

sick birch
potent spear
#

right

manic path
#

bot_.helper_functions is just a list of functions such as [self.a, self.b]

sick birch
#

Try printing something at the top of your hidden_commands function:

    async def hidden_commands(self):
      print("called")
      ...
manic path
#

yep. It's called

manic path
sick birch
#

If that's called, my only other guess is that commands_ is empty

#

Also side note, but you should prefix your variable names with an _, not put it at the end, like _commands, but often times there's no need to even do that

manic path
#

I guess so.

sick birch
#

If you're making a minecraft bot, python may not be the best language

warped mirage
#

can someone help me fix my leveling system

sick birch
#

What's the issue?

warped mirage
#

the event is weird and the command doesnt work at all

#

can i show code ?

sick birch
#

Minecraft is written in Java, not Javascript. If you want to make minecraft bots, you should learn Java. Not to mention minecraft bots may be in violation Mojang's TOS, depending on how it's used

sick birch
warped mirage
#

wdym by making a minecraft bot

warped mirage
#

what is the minecraft bot gonna do

slate swan
#

discord is a website, and has its own API, minecraft does not have anything like that
its just an java app running on ur device

sick birch
#

Exactly like so this

#

Discord is both a website and a desktop app, the latter of which uses Electron

warped mirage
#

robin do u know what possibly could be breaking my bot with the level system

sick birch
#

I'm looking, one moment

#

This reminds me why I always use an ORM 😅

#

I doubt that

flint isle
#

wait how do i bind the data

sick birch
#

It's going to be difficult to create a minecraft bot without knowing java

sick birch
#

If you're not subclassing: bot.var_name = ...

flint isle
#

ummm i dont understand what you mean lol

sick birch
#

@warped mirage sorry, I'm having a difficult time reading the code. Do you get any errors? That may help me figure out what's wrong

sick birch
flint isle
sick birch
#

No, in general, are you subclassing bot?

warped mirage
sick birch
#

You have any error handlers?

warped mirage
#

Nah

sick birch
#

In that case I'm willing to bet this is a logic issue

warped mirage
#

Idk

#

Will a handler rlly help ?

sick birch
#

What handler?

warped mirage
#

Error

sick birch
#

No, it can harm you if you're not careful

#

Sometimes people make a global error handler and it eats up all errors

warped mirage
#

Tf

sick birch
#

Yeah, that's why it's important to be careful with global error handlers

warped mirage
#

I’m so confused lmao

flint isle
# sick birch No, in general, are you subclassing bot?

um i dont know what you mean but this it the code in my bot.py

import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles

# import logging

# logging.basicConfig(level=logging.INFO)


import cogs.whiskey
from colorama import Fore, Back, Style

bot = commands.Bot(command_prefix="$", intents=disnake.Intents.all())
ct = datetime.datetime.now()
guild_ids = []
print('Starting Bot')
print('Connecting to Discord API.')
print('Please Wait')





# Add Cogs

# bot.load_extension('cogs.social')
# bot.load_extension('cogs.chat_room_managment')
# bot.load_extension('cogs.socialv2')
# bot.load_extension('cogs.database')
# bot.load_extension('cogs.embd')
bot.load_extension('cogs.developerfeatures')
bot.load_extension('cogs.events')
print(Fore.YELLOW + '[✓]' + '[Developer Features Cog] ' + Fore.GREEN + 'Loading Complete' + Fore.WHITE)
sick birch
#

Okay, looks like you're not subclassing then

#

You can bind the data using bot.var_name = ...

warped mirage
#

@sick birch so what should I do rn

sick birch
#

Of course replace ... with actual data

sick birch
warped mirage
#

Ok

sick birch
#

Well okay I get why it's sending a message every time

warped mirage
#

?

sick birch
#

It sends a message every single message, as long as the user has a record in the database:

#
if not xp or not level:
  ...
else:
  ...
  await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")
warped mirage
#

Ah so basically add a else : ye ?

sick birch
#

Not quite, you want to add an if statement detailing when the message should be sent

warped mirage
#

It’s meant to be sent when the user earned a level

sick birch
#

Yes, so it should be sent when you UPDATE the database as well

warped mirage
#

Btw do u know why it says level 0 all the time ?

sick birch
#

It takes 100 XP to get to one level right?

#

So it may take a while of you sending random messages

warped mirage
#

Alr so what should I change ?

#

Just add else I guess

flint isle
#

does that go in the main file?

sick birch
sick birch
warped mirage
#
if xp >= 100:
            level += 1
            await client.db.execute("UPDATE levels SET level = ? WHERE user = ? AND guild = ?",
                                (level, author.id, guild.id,))
            await client.db.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?",
                                (0, author.id, guild.id,))
        await client.db.commit()
        await message.channel.send(f"{author.mention} has leveled up to level **{level}**!")```
#

thats my if statement

sick birch
#

That looks about right

#

And also fix the indents

warped mirage
#

i didnt change anything

sick birch
#

it looks different from the pastebin

warped mirage
#

ye its the same tho

sick birch
#

Ah

#

In that case move it all into the if xp >= 100

warped mirage
#

if this helps?

warped mirage
sick birch
#

What errors?

slate swan
warped mirage
#

indent errors lmao

sick birch
sick birch
#

The end goal is to get everything inside the if statement

warped mirage
#

okay , if u say so

slate swan
# sick birch Hm?

isnt it gonna be triggered every time if the xp is above or equal to 100.....there's no point, its gonna perform the same task over and over

sick birch
#

Isn't that the point though? If the XP is greater than or equal to 100, you should increment the level by 1?

#

I think I see what you're saying - you might want to reset XP back to 0 after that

slate swan
sick birch
#

I'm not quite following

slate swan
#

nvm

sick birch
#

Any errors?

flint isle
#

uhhh i see Property 'guilds' cannot be set

guildz = os.getenv('GUILDS')
bot = commands.Bot(command_prefix="$", intents=disnake.Intents.all())
bot.guilds = guildz
sick birch
#

mm

slate swan
# sick birch I'm not quite following

I mean, if xp >= 100 checks if the xp is greater than or equal to 100, and if it is above hundred every time, its gonna add a new level after every message

sick birch
#

XP is reset to 0 when xp >= 100 though

slate swan
#

oh i see

sick birch
#

It's not clear and hidden in the query, so I see where you're coming from

sick birch
#

Ah okay, I thought you could do that. Subclassing would fix that issue

#
class MyBot(commands.Bot):
  def __init__(self, guilds, ...):
    self.guilds = guilds
    super().__init__(command_prefix="...", ...)
bot = MyBot(guilds=...)
warped mirage
#

hey

#

so what should i do someone lemme knwo

#

@sick birch can u tell me lol

sick birch
#

Already did, move it into the if statement

flint isle
warped mirage
flint isle
slate swan
#
@bot.command()
async def setapikey(ctx, apikey):
    cfg = {}
    with open("config.json", "r") as f:
        cfg = json.load(f)

    cfg[str(ctx.guild.id)] = apikey

    with open("config.json", "w") as f:
        json.dump(cfg, f, indent=4)
    await ctx.author.send(f"Successfully set the api key to {apikey}")```
flint isle
slate swan
#

and my issue is in file writing as well

#

so if u help it'd be sexy

flint isle
#

I don't know much so ima let the experts help lol

flint isle
warped mirage
#

@sick birch hey

#

can someone confirm if everything is inside of the if statement

#

or nah

flint isle
#

yes it is

#

from what i see but i may be wrong

warped mirage
#

OMG W

#

MY EVENT WORKS IT DOES THE LEVELS

#

I put everything in the if statement

#

Whoever helped me thanks the event works

#

But my command doesn’t , can yall help me ?

flint isle
#

oof can you put the code here

warped mirage
#

No problem

#

Great things take time I’m greatful I fixed my event atleast

#
@client.command(aliases=['lvl', 'rank', 'r'])
async def level(ctx, member: discord.Member = None):
    member = member or ctx.author
    async with client.db.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?",
                                 (member.id, ctx.guild.id,)) as cursor:
        xp = await cursor.fetchone()
    async with client.db.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?",
                                 (member.id, ctx.guild.id,)) as cursor:
        level = await cursor.fetchone()

    if not xp or not level:
        await client.db.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)",
                                (0, 0, member.id, ctx.guild.id,))
        await client.db.commit()

        try:
            xp = xp[0]
            level = level[0]
        except TypeError:
            xp = 0
            level = 0

        em = discord.Embed(title=f"{member.name}'s level", description=f"Level: `${level}`\nXP: `{xp}`")
        await ctx.send(embed=em)```
#

wait

flint isle
#

what part is not working

warped mirage
flint isle
#
import disnake
from disnake.ext import commands
from colorama import Fore, Back, Style
from datetime import datetime
import time


#below are two date time functions that have different functions but one of them adds to the other durring startup
start_time = datetime.now()
mytime = time.localtime()
if mytime.tm_hour < 12:
    timeofday = 'AM'
else:
    timeofday = 'PM'

class events(commands.Cog):
    """Useful Features for Bot Development."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')

    @commands.Cog.listener()
    async def on_ready(self):
        guild_ids = self.bot
        print(Fore.GREEN + 'Connected!')
        print('Bot is ready!' + Fore.WHITE)
        print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
        embed = disnake.Embed()
        embed.title = f"**Online**"
        embed.set_footer(text="Logging System")
        embed.set_author(name='WhiskeyBot', icon_url=f"{self.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: `{self.bot.user.name}`
        Bot ID: `{self.bot.user.id}`
        Guilds: `{len(self.bot.guilds):,}`
        Users: `{len(list(self.bot.get_all_members()))}`
        Disnake Version: `{disnake.__version__}`
        Loaded Cogs: `{list(self.bot.cogs)}`
        Developer: `whiskeythefox#7339`
        """
        GUILD_ID = 798726719573065749
        CHANNEL_ID = 798726720181633047
        location = self.bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
        await location.send(embed=embed)

    @commands.slash_command(name="uptime", guild_ids=guild_ids)
#

@sick birch ^

#

Did I do that right?

#

did you ask earlier?

#

ok someone else did lmao

#

idk but are you trying to create a custom help command?

#

Ok 1 sec

warped mirage
#

@flint isle my command aint working if u was interested

flint isle
#

i saw. idk how to help sorry

potent spear
warped mirage
heavy shard
potent spear
warped mirage
#

and even stores and levels up properly

#

event gives me peace now xd

potent spear
#

since you put the process_commands in the right place, the commands should respond

warped mirage
#

the level command doesnt tho

#

wanna inspect it?

#

@client.command(aliases=['lvl', 'rank', 'r'])
async def level(ctx, member: discord.Member = None):
    if member is None:
        member = ctx.author
    async with client.db.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?",
                                 (member.id, ctx.guild.id,)) as cursor:
        xp = await cursor.fetchone()
    async with client.db.execute("SELECT level FROM levels WHERE user = ? AND guild = ?",
                                 (member.id, ctx.guild.id,)) as cursor:
        level = await cursor.fetchone()

    if not xp or not level:
        await client.db.execute("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)",
                                (0, 0, member.id, ctx.guild.id,))
        await client.db.commit()

        try:
            xp = xp[0]
            level = level[0]
        except TypeError:
            xp = 0
            level = 0

        em = discord.Embed(title=f"{member.name}'s level", description=f"Level: `${level}`\nXP: `{xp}`")
        await ctx.send(embed=em)```
potent spear
#

seems fine at first sight

warped mirage
#

idk what shall i do

#

when i do >help it shows as a command , but nothing much

paper sluice
heavy shard
potent spear
heavy shard
#

xp is fetch result, it should be tuple of results

potent spear
#

also, your SELECT statement doesn't make much sense

#

you can select multiple columns at once

#

as well as update

#

you don't have to make 2 db executions of that

warped mirage
#

what do i change

flat solstice
#

Does someone mind looking over my code? I have a cog with a few commands which work, a event which doesn't seem to be working and a task loop which I don't think is working. I'm not getting any errors so I'm thinking I have a logic issue that I just can't find.
The code: https://paste.pythondiscord.com/rorenuxega.py

flint isle
#

hmm

Traceback (most recent call last):
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
    from disnake.ext import commands
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
    from .bot import *
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
    class Bot(BotBase, InteractionBotBase, disnake.Client):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
    @guilds.setter
NameError: name 'guilds' is not defined

potent spear
heavy shard
warped mirage
potent spear
warped mirage
flint isle
warped mirage
#

from try:

heavy shard
warped mirage
#

ok no errors

#

lemme test

potent spear
#

you don't want to make a help command like that

junior verge
#

What is that help command

potent spear
#

anyways, you forgot the command decorator

#

but you don't want to hardcode a help command

flint isle
#

lol i sent him that origionally

potent spear
#

I guess he just doesn't want to read

warped mirage
#

LETS GO

junior verge
#

Lmao

warped mirage
#

ALL FIXED …..

paper sluice
warped mirage
#

@heavy shard what a legend

flint isle
# paper sluice show code
import disnake
from disnake.ext import commands
from colorama import Fore
from datetime import datetime
import time


#below are two date time functions that have different functions but one of them adds to the other durring startup
from wb import guild_ids

start_time = datetime.now()
mytime = time.localtime()
if mytime.tm_hour < 12:
    timeofday = 'AM'
else:
    timeofday = 'PM'

class events(commands.Cog):
    """Useful Features for Bot Development."""

    def __init__(self, bot: commands.Bot):
        self.bot = bot
        print('Loading Events cog')

    @commands.Cog.listener()
    async def on_ready(self):
        guild_ids = self.bot
        print(Fore.GREEN + 'Connected!')
        print('Bot is ready!' + Fore.WHITE)
        print(Fore.CYAN + 'Waiting For Commands' + Fore.WHITE)
        embed = disnake.Embed()
        embed.title = f"**Online**"
        embed.set_footer(text="Logging System")
        embed.set_author(name='WhiskeyBot', icon_url=f"{self.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: `{self.bot.user.name}`
        Bot ID: `{self.bot.user.id}`
        Guilds: `{len(self.bot.guilds):,}`
        Users: `{len(list(self.bot.get_all_members()))}`
        Disnake Version: `{disnake.__version__}`
        Loaded Cogs: `{list(self.bot.cogs)}`
        Developer: `whiskeythefox#7339`
        """
        GUILD_ID = 798726719573065749
        CHANNEL_ID = 798726720181633047
        location = self.bot.get_guild(GUILD_ID).get_channel(CHANNEL_ID)
        await location.send(embed=embed)

    @commands.slash_command(name="uptime", guild_ids=guild_ids)
    async def uptime(self, ctx):
        ...


def setup(bot):
    bot.add_cog(events(bot))

      ```
paper sluice
#

where is the guild setter?

flint isle
#

i think thats an internal error for disnake

paper sluice
flint isle
#

mm i pasted the wrong code :/

potent spear
#

still not optimized, but cool

warped mirage
#

now time for rank card finally

hidden snow
#

hey where should i start with when looking to make a simple discord bot?
also does experience matter? I have about a week of experience

potent spear
hidden snow
#

what is oop?

paper sluice
potent spear
slate swan
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50003): Cannot execute action on a DM channel

@bot.command()
async def setapikey(ctx, apikey):
    if isinstance != (ctx.channel, discord.channel.DMChannel):
        await ctx.message.delete()
        await ctx.author.send("WARNING! You can not use this command in the server because it might result in your api key getting leaked!\nReGen your api key and set your api here!")
    elif isinstance(ctx.channel, discord.channel.DMChannel):
     with open('config.json', 'r') as f:
         cfg = json.load(f)

     cfg[str(ctx.author.id)] = apikey

     with open('config.json', 'w') as f:
         json.dump(cfg, f)
     await ctx.send(f"Successfully set the api key to {apikey}")

happens when i use the command in my dms

hidden snow
paper sluice
#

if isinstance != (ctx.channel, discord.channel.DMChannel): pithink pithink pithink

potent spear
#

you should READ YOUR ERROR, then you should've known EXACTLY what line caused it

#

oh hold up

slate swan
paper sluice
potent spear
#

even better

if ctx.channel.type == "private":
  #...
else:
  #...```
potent spear
#

and also use ELSE pls

slate swan
#

i had else but i was testing elif and the statement

#

if it would work

flint isle
#
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv

# import aiohttp
# import aiofiles

# import logging

# logging.basicConfig(level=logging.INFO)


load_dotenv()

guilds = os.getenv('GUILDS')

import cogs.whiskey

from colorama import Fore

load_dotenv()


class MyBot(commands.Bot):
    def __init__(self, guilds):
        self.guilds = guilds
        super().__init__(command_prefix="$", intents=disnake.Intents.all())

bot = commands.Bot(command_prefix="$")


ct = datetime.datetime.now()
guild_ids = []
print('Starting Bot')
print('Connecting to Discord API.')
print('Please Wait')

# Add Cogs

# bot.load_extension('cogs.social')
# bot.load_extension('cogs.chat_room_managment')
# bot.load_extension('cogs.socialv2')
# bot.load_extension('cogs.database')
# bot.load_extension('cogs.embd')
bot.load_extension('cogs.developerfeatures')
bot.load_extension('cogs.events')
print(Fore.YELLOW + '[✓]' + '[Developer Features Cog] ' + Fore.GREEN + 'Loading Complete' + Fore.WHITE)
potent spear
#

you've made a subclass for your bot, but you're never using it...

#
class Shit(commands.Bot):
  # ...

bot = Shit(...)```
flint isle
#

im trying pass a var to the cogs

potent spear
#

sure

#

just
bot = MyBot(guild_ids)

#

you've already hardcoded the command prefix in the init, so no need to pass that anymore

slate swan
#

Im trying to make a discord bot that sends a roblox username and then deletes the username from the file but I dont know how to delete the text!
CODE:

    await ctx.author.send(random_line('roblox.txt') + "\nFORMAT: Username:Password")
random_line('roblox.txt').delete()
potent spear
#

a txt isn't a database

#

you should use a database

slate swan
#

it selects a random line and says it in a server

#

but how do I remove the line so it will never be said again?

potent spear
#

I know you're trying to make some sort of giveaway or whatever, but you should definitely use a database for that

slate swan
#

you put accounts in and when someone runs a command like $roblox it sends them a roblox account from a huge txt file all I need to know is how do I delete that account from the txt after its been sent

potent spear
#

you want to use a database for these kind of things

warped mirage
#

can someone tell me whats wrong im so tired

potent spear
#

user_data["level"] => user_data['level']

#

same goes for the rest of the user data shit

warped mirage
#

First time damn

#

I never used em

potent spear
#

it's just because the f string messes with it

#

it thinks it's already the end of the string if you use "

#

or you can just use singular ' for the outside of the f string
f'My name {person["name"]} and my age {person["age"]}'

slate swan
flint isle
#
C:\Users\Andy\virenv\Scripts\python.exe C:/Users/Andy/PycharmProjects/WhiskeyBotMain/wb.py
Traceback (most recent call last):
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
    from disnake.ext import commands
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
    from .bot import *
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
    class Bot(BotBase, InteractionBotBase, disnake.Client):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
    @guilds.setter
NameError: name 'guilds' is not defined

welp the internal error is still here

potent spear
potent spear
heavy shard
flint isle
#

should i just do env_guilds

slate swan
#

i wanna it except this specific error User is at daily alt limit. how?

flint isle
heavy shard
#

because objects have properties and methods

slate swan
#

doesnt the custom variables get contained in the random amount of kwargs inside of the class's init?

#

I am making a discord bot and I have alot of phrases I want to use in a txt file but I never want the same phrase to be said twice
So I need to delete the phrase from a txt file any ways how?

heavy shard
#

i'm not sure of that

slate swan
unkempt canyonBOT
#

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

1
slate swan
#

thats how i think its done

#

!e

print("TEST")
warped mirage
#

guys i have an error

#

Command raised an exception: AttributeError: 'str' object has no attribute 'url'

slate swan
#

I am making a discord bot and I have alot of phrases I want to use in a txt file but I never want the same phrase to be said twice
So I need to delete the phrase from a txt file any ways how?

potent spear
warped mirage
#
    user_data = {
        "name": f"{member.name}#{member.discriminator}",
        "xp": xp,
        "level": level,
        "next_level_xp": 100,
        "percentage": xp,
    }

    background = Editor(Canvas((900, 300), color="#141414"))
    profile_picture = await load_image_async(str(member.avatar.url))
    profile = Editor(profile_picture).resize((150, 200)).circle_image()

    poppins = Font.poppins(size=40)
    poppins_small = Font.poppins(size=30)

    card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]

    background.poppins(card_right_shape, color="#FFFFFF")
    background.paste(profile, (30, 30))

    background.rectangle((30, 220), width=650, height=40, color="#FFFFFF")
    background.bar((30, 220), maw_width=650, height=40, percentage=user_data["percentage"], color="#FFFFFF", radius=20,)
    
    background.text((200, 40), user_data["name"], font=poppins, color="FFFFFF")

    background.rectangle((200, 100), width=350, height=2, fill="#FFFFFF")
    background.text(
        (200, 130),
        f"Level - {user_data['level']} | XP - {user_data['xp']}/{user_data['next_level_xp']}",
        font = poppins_small,
        color = "#FFFFFF",
    )

    file = discord.File(fp=background.image_bytes, filename="levelcard.png")
    await ctx.send(file=file)```
slate swan
#

My friend made one

#

and it worked but he wont send me it

potent spear
#

if you want to copy his bad implementation, sure

slate swan
#

I have over 300k phrases

#

just checking words in a txt file is fine but manipulating the data, mhm no good

potent spear
warped mirage
potent spear
potent spear
slate swan
warped mirage
#
profile_picture = await load_image_async(str(member.avatar.url))```
#

this

potent spear
#

well, I see it already

slate swan
#

im pretty sure the url property returns a string already

full lily
#

@slate swan You're gonna find yourself in a load of trouble here, trying to evade the rules

warped mirage
#
profile_picture = await load_image_async(member.avatar.url))```
potent spear
#

loading the image can even be done through the .read() method lol

full lily
#

:/

slate swan
#

leave me alone

potent spear
warped mirage
#

idc lol

#

i wanna keep my method

flint isle
# flint isle is this better
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles

# import logging

# logging.basicConfig(level=logging.INFO)


import cogs.whiskey

from colorama import Fore
load_dotenv()


class MyBot(commands.Bot):
    def __init__(self, guilds):
        self.guilds = guilds
        super().__init__(command_prefix="$", intents=disnake.Intents.all(), env_guild = os.getenv('guilds'))

bot = commands.Bot(command_prefix="$")

guilds = os.getenv('GUILDS')
# bot = commands.Bot(command_prefix="$", intents=disnake.Intents.all())
ct = datetime.datetime.now()
guild_ids = []
print('Starting Bot')
print('Connecting to Discord API.')
print('Please Wait')


potent spear
#

you're making it harder than it is

warped mirage
#

so all i do is .read and thats it?

slate swan
potent spear
potent spear
#

even gave examples

flint isle
slate swan
flint isle
warped mirage
#
profile_picture = await load_image_async(member.avatar.url)```
#

bruh i dont see the error in this , still gives the error

potent spear
slate swan
#

that isnt very nice is it?

#

idc

honest laurel
potent spear
unkempt canyonBOT
#

property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
slate swan
full lily
#

stick and stones, rizzy

warped mirage
#

discord.Member.avatar

#

ok

potent spear
#

check the methods of that

slate swan
#

the docs command has 41 packages you need to specify which one

potent spear
unkempt canyonBOT
#

property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.

If the user does not have a traditional avatar, `None` is returned.
If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
flat solstice
slate swan
#

?

#

what is this a role play server?

#

shut up

#

ill rather not

#

Ill slap you like your dad does Oh wai-

#

!ot

unkempt canyonBOT
slate swan
#

back on topic lmao

warped mirage
#

guys i tried many methods it doesnt work

#

someone please help me fix

flint isle
# honest laurel You're creating instance of `commands.Bot` ```py bot = commands.Bot(command_pref...
import disnake
from disnake.ext import commands
import datetime
import os
# import requests
from dotenv import load_dotenv
# import aiohttp
# import aiofiles

# import logging

# logging.basicConfig(level=logging.INFO)


import cogs.whiskey

from colorama import Fore
load_dotenv()
env_guilds = os.getenv('GUILDS')

class MyBot(commands.Bot):
    def __init__(self, env_guilds):
        self.guilds = env_guilds
        super().__init__(command_prefix="$", intents=disnake.Intents.all(), env_guild = os.getenv('guilds'))



bot = MyBot(env_guilds)
ct = datetime.datetime.now()
guild_ids = []
``` Did i do the right?
warped mirage
#
 user_data = {
        "name": f"{member.name}#{member.discriminator}",
        "xp": xp,
        "level": level,
        "next_level_xp": 100,
        "percentage": xp,
    }

    background = Editor(Canvas((900, 300), color="#141414"))
    profile_picture = await load_image_async(member.avatar.url)
    profile = Editor(profile_picture).resize((150, 200)).circle_image()```whats wrong here
slate swan
#

lol it got caught by the filter

warped mirage
daring olive
unkempt canyonBOT
#

:incoming_envelope: :ok_hand: applied ban to @reef bluff until <t:1654378383:f> (13 days and 23 hours).

slate swan
#

thank you mina!

warped mirage
#
 user_data = {
        "name": f"{member.name}#{member.discriminator}",
        "xp": xp,
        "level": level,
        "next_level_xp": 100,
        "percentage": xp,
    }

    background = Editor(Canvas((900, 300), color="#141414"))
    profile_picture = await load_image_async(member.avatar.url)
    profile = Editor(profile_picture).resize((150, 200)).circle_image()``` whats wrong here, anyone
flint isle
#

error handler to push a message. idk how to build one lol tho

potent spear
#

don't forget to add an
else: raise error in the error handler, you're hiding all the other errors

warped mirage
#

it was member.avatar_url

potent spear
#

so you're on v 1.7.3

flint isle
potent spear
flint isle
#

Oh I didn't understand it originally but when I reread the code that was word wrapped I saw that. Would I remove the line with self.guilds or replace it with something else

potent spear
#

just use variable name that doesn't exist already

warped mirage
potent spear
#

and also, EVERY guidance in this channel matters, don't just "ignore and ask again later on"

flint isle
flint isle
potent spear
flint isle
#

Ok

warped mirage
#

@potent spear any ideas

#

It deletes the xp for some reason idk why

potent spear
#

debug my guy, debug

warped mirage
#

Huh

potent spear
#

just check what happens where, it's not that hard

#

line per line, go over it

warped mirage
#

I checked

#

Nothing seems wrong

potent spear
#

just print the xp right before you'd use a database command or whatever to verify that is in fact all the correct values

warped mirage
#

yourself*

heavy shard
flint isle
warped mirage
#

Will this fix it then ?

heavy shard
#

it should

warped mirage
#

Ok

potent spear
flint isle
heavy shard
#

just bot.the_name_you_used

#

or however you named the bot variable

flint isle
#

!paste

flint isle
potent spear
heavy shard
#

same for guild_ids = bot.custom_guilds in a cog, self.guild_ids = bot.custom_guilds

regal pulsar
#

hello

potent spear
#

you don't have to define guild_ids again in the cog, let me tell you that

radiant shuttle
#

good host for bots to suggest me?

cloud dawn
radiant shuttle
#

is it free or not

cloud dawn
#

No vps aren't free

radiant shuttle
#

and free?

cloud dawn
#

I don't recommend any "free" hosting solutions, sorry.

#

You can look for trails like AWS.

flint isle
potent spear
cloud dawn
slate swan
flint isle
#

XD

heavy shard
#

calls 911

potent spear
#

and your subclassed bot's init should look like

class Shit(commands.Bot):
  def __init__(custom_guild_ids, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.custom_guild_ids = custom_guild_ids```
#

if this isn't a spoonfeed, I don't know what is

cloud dawn
#

9/10 use cog_load.

potent spear
#

he just wants to add that stinky botvar in every cog, because else he thinks he can't access it, which isn't true

#

once defined in the main class, you can just access that variable wherever an instance of your bot class is

cloud dawn
#

Facts.

#

But i doubt he is subclassing Bot so..

#

!botvar

unkempt canyonBOT
#

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

flint isle
#
C:\Users\Andy\virenv\Scripts\python.exe C:/Users/Andy/PycharmProjects/WhiskeyBotMain/wb.py
Traceback (most recent call last):
  File "C:\Users\Andy\PycharmProjects\WhiskeyBotMain\wb.py", line 2, in <module>
    from disnake.ext import commands
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\__init__.py", line 12, in <module>
    from .bot import *
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 57, in <module>
    class Bot(BotBase, InteractionBotBase, disnake.Client):
  File "C:\Users\Andy\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\bot.py", line 183, in Bot
    @guilds.setter
NameError: name 'guilds' is not defined

i still dont know what i broke

potent spear
#

code?