if I input !3people Job Offer I got this image's error. Please resolve my error.
My OS is windows 10 home and discord.py version is 1.0.1
Thank you.
if m.content.startswith('!') and 'Job Offer' in m.content:
if m.content\[1\].isdigit()!=True or int(m.content\[1\]) > 3 or int(m.content\[1\]) <= 0:
embed = discord.Embed(color=0x06afff)
embed = discord.Embed(title="Squad", color=0x06afff)
embed.add_field(name="warning", value="Please input correct value.", inline=False)
await m.channel.send(embed=embed)
else:
comment = ''
for i in m.guild.voice_channels:
if m.author in i.members:
embed = discord.Embed(title="Squad", color=0x06afff)
print(i.create_invite())
embed.add_field(name="Squad", value=(await i.create_invite()), inline=False)
print(i)
embed.add_field(name="Title", value=i, inline=False)
cnt=4-int(m.content\[1\])
embed.add_field(name="user count", value='%d /4'%(cnt), inline=False)
if 'Job Offer' in m.content:
comment = m.content.split('Job Offer')\[1\]
if len(comment) == 0:
comment = 'Today's finish is chicken'
embed.add_field(name="Comment", value=comment, inline=False)
await m.channel.send(embed=embed)
await m.channel.send('#here')
Error Image
create_invite is a coroutine so it needs to be awaited.
The simple fix is to edit line 12:
print(await i.create_invite())
Adding the await before i.create_invite() should solve the issue.
Related
so i tried to make a spam function and run it but it just gives this error: RuntimeWarning: coroutine 'spam' was never awaited
spam(channel)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
and no message is being sent.
this is the code:
await guild.create_text_channel("NEEDLESS-NUKER")
for channel in guild.text_channels:
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
amount = 500
for i in range(amount):
await guild.create_text_channel(random.choice(SPAM_CHANNEL))
spam(channel)
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
print(f"{c.YELLOW}[{date}]{c.GREEN} Nuked {guild.name} Successfully.")
return
async def spam(channel):
for i in range(15):
try:
names = json.loads(open("words.json").read())
SPAM_MESSAGE = [
"#everyone LOL GET NUKED :skull::skull:",
"#everyone LOL IMAGINE GETTING NUKED :skull::skull:",
"lol hahaha get nuked",
f"im {random.choice(names)}",
f"Lol this is so random like {random.choice(names)}#{random.randint(1, 1000)} :skull:",
f"Made By {random.choice(names)}!",
]
msg = random.choice(SPAM_MESSAGE)
await channel.send(msg)
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
print(f"{c.YELLOW}[{date}]{c.GREEN} Succeffully send {msg}")
except Exception as e:
names = json.loads(open("words.json").read())
SPAM_MESSAGE = [
"#everyone LOL GET NUKED JOIN https://dsc.gg/pythondevs",
"#everyone LOL IMAGINE GETTING NUKED :skull::skull:",
"#everyone https://dsc.gg/pythondevs",
f"#everyone im {random.choice(names)}",
f"#everyone Lol this is so random like {random.choice(names)}!{random.randint(1000, 10000)}",
f"#everyone Made By {random.choice(names)}!",
]
msg = random.choice(SPAM_MESSAGE)
date = str(datetime.now()).split(".")[0]
date = date.split(" ")[1]
print(f"{c.YELLOW}[{date}]{c.RED} Failed Sending Message {msg} exc: {e}")
first it was #client.event and then on_guild_channel_create(channel) and it worked but now it wont work i changed it because everytime i created a channel with this bot it would send 15 messages in the channel and if i make a voice channel it just gives me an error.
so please help me fix this. Thanks.
You're calling an async function, so you need to create_task it or await it.
import asyncio
import time
async def wait:
time.sleep(1)
await asyncio.sleep(1)
return None
result = asyncio.create_task(wait()) #Wait 1 second.
await wait() #Wait 2 seconds because it will wait for execution to end.
In your case, you would need to change line 8 from (8th line of the answer)
spam(channel)
to
await spam(channel)
Hello I recently made a help command using discord_components buttons (I know they arent fully supported by Discord.py) but I still went ahead. The problem is that whenever I run the command and receive the Buttons to click on, they alway say "This Interaction Failed". I can't seem to find what's wrong. Please help.
Thanking You,
NightMX.
import discord
from discord.ext import commands
from discord_components.component import ButtonStyle
from discord_components import DiscordComponents, Button, Select, SelectOption
from discord_components.interaction import InteractionType
class BotCommands(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def helpv2(self, ctx):
funbutton = Button(style=ButtonStyle.grey, label="Fun Commands", id="funcmds")
monkedevbutton = Button(style=ButtonStyle.grey, label="Attachment Commands", id="monkecmds")
# utilitybutton = Button(style = ButtonStyle.grey, label = "3", id = "embed3")
funembed = discord.Embed(title="Fun Commands", colour=discord.Colour.orange())
funembed.add_field(name="k.joke", value="Sends a Random joke from PyJokes")
monkedevembed = discord.Embed(title="Fun Commands", colour=discord.Colour.blurple())
monkedevembed.add_field(name="k.dog", value="Sends a Random Dog Fact")
monkedevembed.add_field(name="k.monkey", value="Sends a Monkey's Picture")
monkedevembed.add_field(name="k.bird", value="Sends a Bird's Picture")
await ctx.send(
"Kola's Beta Help Command!",
components=[[funbutton, monkedevbutton]]
)
buttons = {
"funcmds": funembed,
"monkedcmds": monkedevembed
}
while True:
event = await self.bot.wait_for('button_click')
if event.channel is not ctx.channel:
return
if event.channel == ctx.channel:
response = buttons.get(event.component.id)
if response is None:
await event.channel.send(
"Something went Wrong"
)
if event.channel == ctx.channel:
await event.respond(
type=InteractionType.ChannelMessageWithSource, embed=response
)
def setup(client):
client.add_cog(BotCommands(client))
should be content="something" instead of embed = response
So I saw this fields columns in some embed and I realized that my embeds are boring. My question is - how this columns are made? is it an image or something? how can I add these columns to my embeds? Are these emojis? if so where can I get them? I know I ask too many questions but I am just curious. Thanks
You can use the > symbol to make those columns.
I've remade the embed shown in the picture:
import discord, datetime
from discord.ext import commands
client = discord.ext.commands.Bot(command_prefix = "!");
#client.command()
async def embed(ctx):
embed = discord.Embed(
title = "Deep Stone Crypt Void Run",
description = "All void subclass run of Deep Stone Crypt for the triumph.\nExperience optional.",
colour = discord.Colour.from_rgb(241,196,15)
)
embed.add_field(name="Time", value="Mon Dec 7th, 2020 • 6pm - 9pm PST (UTC-8)", inline=False)
embed.add_field(name="Links", value="[Add to calender](https://discordapp.com)\n[Convert time zone](https://discordapp.com)", inline=False)
embed.add_field(name="\✅ Accepted (4/6)", value="> TMC\n> ArcaneVoid\n> LilRemsy\n> Asal", inline=True)
embed.add_field(name="\❌ Declined (2)", value="> Joe_Hammersmash\n> Jeiyiu", inline=True)
embed.add_field(name="\❔ Tentative (2)", value="> Awoken Phoenix\n> datigren186", inline=True)
embed.set_footer(text="Created by TMC\nLocal time")
embed.timestamp = datetime.datetime.now()
await ctx.send(embed=embed)
client.run("token_here")
Output:
Check out this article to learn more about Discord markdown.
I have a music bot that streams radio and each stream is a command for ease of use. The problem is that there are 100+ stations now and it's getting increasingly more difficult to update the code for each one.
#bot.command(aliases=["VAR1", "VAR2"])
#commands.check(if_channel_private)
async def VAR(ctx):
current_time = datetime.now().strftime("%H:%M")
station = 'VAR3'
if len(embed_history.fields) <= 4:
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
elif len(embed_history.fields) > 4:
embed_history.remove_field(0)
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
stream = 'URL VAR4'
resume = stream
if len(pause_list) != 0 or len(radio_station) != 0:
pause_list.clear()
radio_station.clear()
voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
try:
voice.play(FFmpegPCMAudio(stream))
print(f'Playing {station}')
except:
print(f"An error occurred while trying to play {station}")
await ctx.send(error_message)
radio_station.append(station)
pause_list.append(resume)
embed_st.clear_fields()
embed_st.add_field(inline=False, name=embed_name,
value="VAR5")
await ctx.send(embed=embed_st)
#VAR.error
async def _pr_error(ctx, error):
if isinstance(error, commands.CheckFailure):
if ctx.message.author.voice is None:
return
await ctx.send(f"Only users in __the same private voice channel__ can change the station!")
else:
await ctx.send(f"```css\n"
"[ERROR: Unexpected error has occured!]"
"```")
print(error)
This is how it looks like for each station. Is it possible to write this only once and then call it for every station? And only to have to change the variables (VAR)? Otherwise, it bloats the whole text file with repetitive code...
I don't check this code, but may be it's work. Create function, and send to it your variables station and stream:
#bot.command(aliases=["VAR", "VAR"])
#commands.check(if_channel_private)
async def VAR(ctx):
await some_function('VAR', 'URL_VAR')
# Your function for all stations
async def some_function(station, stream):
current_time = datetime.now().strftime("%H:%M")
if len(embed_history.fields) <= 4:
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
elif len(embed_history.fields) > 4:
embed_history.remove_field(0)
embed_history.add_field(inline=False, name=f"[{current_time}] Played:", value=f'`{station}`')
resume = stream
if len(pause_list) != 0 or len(radio_station) != 0:
pause_list.clear()
radio_station.clear()
voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing():
voice.stop()
try:
voice.play(FFmpegPCMAudio(stream))
print(f'Playing {station}')
except:
print(f"An error occurred while trying to play {station}")
await ctx.send(error_message)
radio_station.append(station)
pause_list.append(resume)
embed_st.clear_fields()
embed_st.add_field(inline=False, name=embed_name,
value="VAR")
await ctx.send(embed=embed_st)
I've got a problem with discord.py bot, client.event on_message commands work perfectly for me but client.command() doesnt work, I've tried reinstalling everything from python to anaconda but it still doesnt work. (and sorry if question and code was messy I'm sort of new to programming and stackoverflow)
code:
import discord
import random
import time
from discord.ext import commands
import discord.utils
songs = []
songs_string = """HaB
LionNorth
Stalingrad
"""
i2 = 0
for song_name in songs_string.splitlines():
songs.insert(i2, song_name)
i2 += 1
list1 = []
help = '''
все команды должны начинаться с точки
dsw сюда ругательство,что бы добавить новое ругательство в sw на время сессии бота
time узнать текущее время
sabaton для получения случайной песни Сабатон (иногда может не работать из-за размера файла)
sw чтобы получить случайную ругань
'''
i = 0
string = f'''ПИДОРАС
ПОШЕЛ НАХУЙ
ДА ТЫ УЕБОК
не интересно,пидор
НАЧАЛЬНИК БЛЯТЬ,ЭТОТ ПИДОРАС ОБОСРАЛСЯ
бля ахуительная история
Я ТВОЙ НАЧАЛЬНИК
КТО БУДЕТ СОСАТЬ
ПОШЕЛ НА РАБОТУ
ЧИСТИ ГОВНО
НИХУЯ НЕ МОЖЕШЬ,ПОШЕЛ НАХУЙ
я с этим гондоном сидеть не буду бля
какие нахуй корабли?
'''
quotes_string = """Недостаточно овладеть премудростью, нужно также уметь пользоваться ею.
Тем, кто хочет учиться, часто вредит авторитет тех, кто учит.
Трудно быть хорошим..
"""
for word in string.splitlines():
list1.insert(i, word)
i += 1
restr = ["поговорим-по-душам", "🤓флудилка🤓", "⚠правила⚠", "🗯новости🗯"]
client = commands.Bot(command_prefix=".")
#client.command()
async def hi(ctx):
await ctx.send('Hi!')
#client.event
async def on_member_join(member):
for channel in member.guild.channels:
if str(channel) == "welcome":
await channel.send(f"""Welcome to the server {member.mention}""")
#client.event
async def on_message(message):
if str(message.channel) not in restr:
if message.content == ".sabaton":
random.seed(time.time())
randnum = random.randint(0, len(songs) - 1)
await message.channel.send(file=discord.File(songs[randnum]))
elif message.content == ".sw":
random.seed(time.time())
randnum = random.randint(0, len(list1) - 1)
await message.channel.send(list1[randnum].upper())
elif message.content == ".time":
await message.channel.send(f"Current time is {time.localtime()}")
elif message.content == ".help":
await message.channel.send(help)
if message.content.startswith(".dsw"):
msg = message.content.split()
output = ''
for word in msg[1:]:
output += word
output += ' '
await message.channel.send(f"{output} было добавлено в список ругательств на эту сессию")
list1.append(output)`
client.run("token here")
When using an on_message event, you'll need the bot to process_commands() if you're planning on using command decorators:
#client.event
async def on_message(message):
await client.process_commands(message)
# rest of your on_message code
References:
on_message
Bot.process_commands() - "Without this coroutine, none of the commands will be triggered. If you choose to override the on_message() event, then you should invoke this coroutine as well."