I have a problem with my bot because I don't want to load certain variables that are specified. If you see any errors in the code, I'd be very grateful if you could help.
Error: discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
Here is code:
#!/usr/bin/python
import os
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('')
bot = commands.Bot(command_prefix = "/")
client = commands.Bot(command_prefix = "/")
#bot.event
async def on_ready():
print("----------------------")
print("Zalogowano jako:")
print("Użytkownik: %s"%client.user.name)
print("ID: %s"%client.user.id)
print("----------------------")
#bot.command(name='tutorial', help='Tutorial')
async def tutorial(ctx, member: discord.Member):
message = await ctx.send('flag_gb In which language do you want to receive the instructions?')
message = await ctx.send('flag_gb W jakim języku chcesz otrzymać instrukcje?')
flag_pl = 'flag_pl'
flag_gb = 'flag_gb'
await message.add_reaction(flag_pl)
await message.add_reaction(flag_gb)
def check(reaction, user):
return user == ctx.author and str(
reaction.emoji) in [flag_pl, flag_gb]
member = ctx.author
while True:
try:
reaction, user = await client.wait_for("reaction_add", timeout=10.0, check=check)
if str(reaction.emoji) == flag_pl:
em = discord.Embed(tittle = "flag_pl", description = "**1**")
em.add_field(name = "Opcja 1", value = "Link" );
await member.send(embed=em)
if str(reaction.emoji) == flag_gb:
em = discord.Embed(tittle = "flag_gb", description = "**2**")
em.add_field(name = "Opcja 2", value = "Link" );
await member.send(embed=em)
except:
print("Wystapil blad!")
bot.run('TOKEN')
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing means that you have to put the name of the member after the command (e.g. /tutorial user123 instead of /tutorial #user123). Also, an error you made is in
flag_pl = 'flag_pl'
and
flag_gb = 'flag_gb'
The emojis in discord always begin and end with :, so it should be
flag_gb = ':flag_gb:'
and
flag_pl = ':flag_pl:'
Related
I am trying to build a Discord bot that takes the /create and generates images using the OpenAI DALL-E model, based on the user's input. However, after the bot prompts the message "What text would you like to generate an image for?", I input the text, but I get the error "Failed to generate image". What can I do? Thank you!
This is code that functions:
import os
import json
import requests
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
#bot.command(name='create')
async def create_image(ctx):
await ctx.send("What text would you like to generate an image for?")
def check(m):
return m.author == ctx.author and m.channel == ctx.channel
try:
text = await bot.wait_for('message', check=check, timeout=60.0)
except asyncio.TimeoutError:
await ctx.send("Timed out, please try again.")
return
text = text.content
api_key = os.environ.get("API_KEY")
headers = {"Content-Type": "application/json"}
data = """
{
"""
data += f'"model": "image-alpha-001",'
data += f'"prompt": "{text}",'
data += """
"num_images":1,
"size":"1024x1024",
"response_format":"url"
}
"""
resp = requests.post(
"https://api.openai.com/v1/images/generations",
headers=headers,
data=data,
auth=("", api_key),
)
if resp.status_code != 200:
await ctx.send("Failed to generate image.")
return
response_text = json.loads(resp.text)
image_url = response_text['data'][0]['url']
await ctx.send(image_url)
bot.run('TOKEN')
I'm fairly new to python and I can't seem to figure out how to make this work. any help?
I'm trying to make a command that makes my discord bot display a random image from a folder. There are around 2000 images in the folder. I want everyone to be able to use the command only once. The images are all unique and I don't want people getting the same image. how would I do this?
# Import Discord Package
import discord
from discord.ext import commands
# Client
client = commands.Bot(command_prefix='/')
# Display random image
# Command that shows Mintbot's version
#client.command(name='version')
async def version(context):
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await context.message.channel.send(embed=myEmbed)
# Welcome Message
#client.event
async def on_ready():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Hello, Mintbot here!')
# Disconnect message
#client.event
async def on_disconnect():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Turning Off')
# Mintbot Version - Embed
#client.event
async def on_message(message):
if message.content == 'what version is mintbot?':
general_channel = client.get_channel(931259149260554283)
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await general_channel.send(embed=myEmbed)
await client.process_commands(message)
# Run the client on the server
client.run('mytoken')
Make sure that you have a json file named " list.json ".
import discord
from discord.ext import commands
import os
import json
import random
# Client
client = commands.Bot(command_prefix='/')
# Reading images
directory = "images" # Change this to your folder directory without / on the end
img = []
total_img = -1
for filename in os.listdir(directory):
img += [filename]
total_img += 1
# Display random image
#client.command()
async def image(context):
with open("list.json", "r") as f:
sent = json.load(f)
if not str("sent") in sent:
sent = {}
sent["sent"] = []
with open("list.json", "w") as f:
json.dump(sent, f , indent=4)
with open("list.json", "r") as f:
sent = json.load(f)
if not str(context.author.id) in sent:
sent[str(context.author.id)] = True
with open("list.json", "w") as f:
json.dump(sent, f , indent=4)
data = sent["sent"]
random_number = None
tries = 0
while random_number == None:
tries += 1
number = random.randint(0, total_img)
if not number in data:
random_number = number
if int(tries + 1) == total_img:
await context.send("All pictures has been sent")
return
file = discord.File(f"{directory}/{img[random_number]}")
await context.send(file=file)
sent["sent"] += [random_number]
with open("list.json", "w") as f:
json.dump(sent, f , indent=4)
# Command that shows Mintbot's version
#client.command(name='version')
async def version(context):
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await context.message.channel.send(embed=myEmbed)
# Welcome Message
#client.event
async def on_ready():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Hello, Mintbot here!')
# Disconnect message
#client.event
async def on_disconnect():
general_channel = client.get_channel(931259149260554283)
await general_channel.send('Turning Off')
# Mintbot Version - Embed
#client.event
async def on_message(message):
if message.content == 'what version is mintbot?':
general_channel = client.get_channel(931259149260554283)
myEmbed = discord.Embed(title="Mintbot", description="Test version", color=800080)
myEmbed.add_field(name="Version Code", value="v1.0.0", inline=False)
myEmbed.set_footer(text="Work In Progress!")
await general_channel.send(embed=myEmbed)
await client.process_commands(message)
# Run the client on the server
client.run(token)
So, I'm making a reaction role command and it keeps giving me the same error,I have enabled intents. members, everything I need but still it gives me the same error.I dont know why its giving me this error,maybe its a bug or somethng??. Well I hope I cant get a answer from here it only hope rn >.<.(this is just to fill the "please add more details thing..sefsdfysdhfjawsdygdefshdgf)
The code :
import discord
from discord.ext import commands
import random
from io import BytesIO
import DiscordUtils
from discord.utils import get
import os
import asyncio as asyncio
import aiohttp
import datetime
import json
intents = discord.Intents.all()
intents.members = True
client = discord.Client(intents=intents)
client = commands.Bot(command_prefix="?",case_insensitive = True)
client.remove_command("help")
#client.event
async def on_raw_reaction_add(payload):
if payload.member.bot:
pass
else:
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(
payload.guild_id).roles, id=x['role_id'])
await payload.member.add_roles(role)
#client.event
async def on_raw_reaction_remove(payload):
guild = client.get_guild(payload.guild_id)
print("Guild checked.")
member = guild.get_member(payload.user_id)
print("Member checked.")
with open('reactrole.json') as react_file:
data = json.load(react_file)
for x in data:
if x['emoji'] == payload.emoji.name:
role = discord.utils.get(client.get_guild(payload.guild_id).roles, id=x['role_id'])
print("got the role")
await member.remove_roles(role)
#client.command(aliases = ['rr'])
#commands.has_permissions(administrator=True, manage_roles=True)
async def reactrole(ctx, emoji, role: discord.Role, *, message):
emb = discord.Embed(title = "REACTION ROLE !",description=message,timestamp = datetime.datetime.utcnow(),color = 0xADD8E6)
emb.set_thumbnail(url = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQPiUxyDTBu4dkC8f3tBeOzM8b0sEnK_8iLUg&usqp=CAU")
emb.set_footer(icon_url = ctx.author.avatar_url, text = f"reactrole embed created by : {ctx.author.name}")
emb.set_image(url = "https://www.logolynx.com/images/logolynx/f8/f843b4dd5ec5dc4e56a3f5639341516a.png")
msg = await ctx.channel.send(embed=emb)
await msg.add_reaction(emoji)
with open('reactrole.json') as json_file:
data = json.load(json_file)
new_react_role = {'role_name': role.name,
'role_id': role.id,
'emoji': emoji,
'message_id': msg.id}
data.append(new_react_role)
with open('reactrole.json', 'w') as f:
json.dump(data, f, indent=4) ```
and heres the error:
Guild checked.
Member checked.
got the role
Ignoring exception in on_raw_reaction_remove
Traceback (most recent call last):
File "C:\Users\pangh\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\pangh\Desktop\Engineer\Engineer.py", line 256, in on_raw_reaction_remove
await member.remove_roles(role)
AttributeError: 'NoneType' object has no attribute 'remove_roles'
The member attribute isn't available in the on_raw_reaction_remove event.
What you can do instead is
Figure out whether to give or remove the role both in on_raw_reaction_add, when a user reacts check if they have the role, if not add if they do then remove the role. Then remove their reaction from the message. This would essentially be a toggle reaction role.
OR
Use the payload.user_id and fetch the member using await fetch_user(user_id).
I have the problem, that when i use discord.utils.get(bot.voice_clients, guild=guild) it is returning None, even when it's connected. I wanna let the bot reconnect to a voice channel, because the bot is getting kicked after around 3-4 hours. I tried to let it reconnect to the channel using a file which contains the name of the channel to reconnect to.
import discord
from discord.ext import commands
from discord.utils import get
import asyncio
import os
import nacl
from keep_alive import keep_alive
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print('Logged in as {0.user}'.format(bot))
#bot.command(aliases=['shreksophone'])
async def shrek(ctx, *, join_channel: str=None):
voice = get(bot.voice_clients, guild=ctx.guild)
global guild_for_reconnect, guild_for_reconnect_voice_channels
guild_for_reconnect = str(ctx.guild)
guild_for_reconnect_voice_channels = ctx.guild.voice_channels
guild_id = str(ctx.guild.id)
author_id = str(ctx.author.id)
async def shrek_repeat(ctx):
f = open('shrek_counter', 'r+')
counter = f.read()
new_counter = int(counter) + 1
f.seek(0)
f.truncate()
f.write(str(new_counter))
f.close()
voice.play(discord.FFmpegPCMAudio('songs/1 hour of shreksophone.m4a'), after=lambda e: asyncio.run(shrek_repeat(ctx)))
if not os.path.exists(guild_id):
f = open(guild_id, 'w')
f.write(author_id)
f.close()
f = open(guild_id, 'r')
session_author = f.read()
f.close()
if session_author == author_id:
if voice is None:
if join_channel is None:
if ctx.author.voice:
channel = ctx.message.author.voice.channel
await channel.connect()
await ctx.send('Playing shreksophone now in "' + channel.name + '" repeatedly.')
print('Playing shreksophone now repeatedly in ' + ctx.guild.name + '.')
voice = get(bot.voice_clients, guild=ctx.guild)
voice.play(discord.FFmpegPCMAudio('songs/1 hour of shreksophone.m4a'), after=lambda e: asyncio.run(shrek_repeat(ctx)))
f = open(guild_for_reconnect + ' channel', 'w')
f.write(str(channel))
f.close()
bot.loop.create_task(voice_reconnect())
else:
await ctx.send('You have to be in a voice channel, if you want me to play shreksophone.')
print('User is not in a voice channel.')
else:
channel = get(ctx.guild.voice_channels, name=join_channel)
channel_exist = get(ctx.guild.voice_channels, name=join_channel)
while channel_exist is None:# the code here just continues with other possibilities
async def voice_reconnect():
while True:
if os.path.exists(guild_for_reconnect + ' channel'):
voice = get(bot.voice_clients, guild=guild_for_reconnect)
f = open(guild_for_reconnect + ' channel', 'r')
channel = f.read()
f.close()
channel_to_reconnect = get(guild_for_reconnect_voice_channels, name=channel)
if voice is None:# so even if the bot is connected it still returns None
await channel_to_reconnect.connect()
if voice.channel.name is not str(channel_to_reconnect):
await voice.move_to(channel_to_reconnect)
await asyncio.sleep(0.25)
How can I edit an embed message multiple times? So far, I have been able to edit an embed message once, but it won't do it again.
Here's the code:
# IMPORTING
import discord
from discord import Embed
from discord.ext import commands
TOKEN = ""
BOT_PREFIX = "!"
bot = commands.Bot(command_prefix=BOT_PREFIX)
from discord import Embed
#commands
#bot.command()
async def test(ctx):
first_embed = Embed(title='embed 1')
second_embed = Embed(title='embed 2')
third_embed = Embed(title='embed 3')
msg = await ctx.send(embed=first_embed)
msg = await msg.edit(embed=second_embed)
await msg.edit(embed=third_embed)
#running the bot
bot.run(TOKEN)
Results: (embed with the title, "embed 2") and an error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'edit'
How can I make it edit the message as embed 3?
Message.edit doesn't return anything, you shouldn't assign msg again,
first_embed = Embed(title='embed 1')
second_embed = Embed(title='embed 2')
third_embed = Embed(title='embed 3')
msg = await ctx.send(embed=first_embed)
await msg.edit(embed=second_embed)
await msg.edit(embed=third_embed)