I made a few commands for my discord bot. When I Send the command .y or .j6 for the 2nd time it pushes the first one with the second. How can I fix this?
(I need to post more details but i dont have them so i write this so i can post this so dont read this because this is trash)
import discord
from discord.ext import commands
from discord_webhook import DiscordWebhook, DiscordEmbed
async def on_ready():
print('Bot is ready.')
client = commands.Bot(command_prefix= '.')
webhook_urls = ['https://discordapp.com/api/webhooks/694265463936647289/zwRbi6A_jHp9r7kbTwOlWir9rS3-cXtMa6XLHHmrzwgyJtQaLPiisbSQBRgq7v39F6MG', 'https://discordapp.com/api/webhooks/699705671440138291/52awf2UE2TgVhumFQKp8ZOo-lz4iBtjt786NC1W1TDElAKCx4spXLP3RNi7O4avuQpHo']
webhook = DiscordWebhook(url=webhook_urls)
#client.command()
async def ping(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
#client.command()
async def raffle(ctx, link, store, sneaker, raffletype ):
channel = client.get_channel(642837709198721034)
embed = discord.Embed(
title=sneaker,
description=store,
url=link,
colour=discord.Colour.blue()
)
embed.add_field(name="Release type", value=raffletype)
embed.set_footer(text='The Hypesply | Chip#4600')
await channel.send(embed=embed)
#client.command()
#commands.has_role('Owner')
async def j6(ctx, link, store, raffletype ):
embed = DiscordEmbed(
title="Nike AirJordan 6 'DMP'",
url=link,
colour=discord.Colour.blue()
)
embed.add_embed_field(name="Store", value=store)
embed.add_embed_field(name="Release type", value=raffletype)
embed.set_thumbnail(url="https://static.sneakerjagers.com/products/660x660/126329.jpg")
embed.set_footer(text='The Hypesply | Chip#4600')
webhook.add_embed(embed)
webhook.execute()
#client.command()
#commands.has_role('Owner')
async def y(ctx, link, store, raffletype):
embed = DiscordEmbed(
title="Adidas Yeezyboost 350 V2 'Linen'",
url=link,
colour=discord.Colour.blue()
)
embed.add_embed_field(name="Store", value=store)
embed.add_embed_field(name="Release type", value=raffletype)
embed.set_thumbnail(url="https://static.sneakerjagers.com/products/660x660/155433.jpg")
embed.set_footer(text='The Hypesply | Chip#4600')
webhook.add_embed(embed)
webhook.execute()```
Related
I have been working on a simple music bot for discord, and my friends requested a feature where you can stream audio from a youtube live stream. This has had me puzzled, and I can't find any good sources to solve this. Here is the important code:
from discord.ext import commands
from discord.ext import tasks
import discord
from itertools import cycle
import os
from dotenv import load_dotenv
import asyncio
from ytsearch import searchr
from discord.utils import get
from discord import FFmpegPCMAudio
from youtube_dl import YoutubeDL
list_to_play = []
paused = False
load_dotenv()
TOKEN = os.getenv("TOKEN")
bot = commands.Bot(command_prefix='-')
#bot.event
async def on_ready():
for guild in bot.guilds:
print(
f'{bot.user} is connected to the following guild(s):\n'
f'{guild.name}(id: {guild.id})'
)
change_status.start()
play_the_list.start()
status = cycle(['Music is here!','More features soon!'])
#tasks.loop(seconds=10)
async def change_status():
await bot.change_presence(activity=discord.Game(next(status)))
async def playa(ctx,url):
YDL_OPTIONS = {'format': 'bestaudio', 'noplaylist': 'True'}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
voice = get(bot.voice_clients, guild=ctx.guild)
with YoutubeDL(YDL_OPTIONS) as ydl:
info = ydl.extract_info(url, download=False)
URL = info['url']
voice.play(FFmpegPCMAudio(URL, **FFMPEG_OPTIONS))
voice.is_playing()
#tasks.loop(seconds=3)
async def play_the_list():
global list_to_play
if paused == False:
if len(list_to_play) != 0:
ctx = list_to_play[0][1]
voice = get(bot.voice_clients, guild=ctx.guild)
if voice.is_playing() == False:
if len(list_to_play) != 0:
await playa(list_to_play[0][1],list_to_play[0][0])
del list_to_play[0]
bot.run(TOKEN)
I'm looking for something like playa() (or ways to edit playa() so it plays live videos)
I would recommend checking out the official example for such a player:
https://github.com/Rapptz/discord.py/blob/master/examples/basic_voice.py
These snippets might help :)
For the FFmpeg Class:
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
and
filename = data['url'] if stream else ytdl.prepare_filename(data)
Command:
#commands.command()
async def stream(self, ctx, *, url):
"""Streams from a url (same as yt, but doesn't predownload)"""
async with ctx.typing():
player = await YTDLSource.from_url(url, loop=self.bot.loop, stream=True)
ctx.voice_client.play(player, after=lambda e: print(f'Player error: {e}') if e else None)
await ctx.send(f'Now playing: {player.title}')
Im trying to make a public bot, and i would want this ticket system witha logging channel it already has a logging channel but how can i modify this to make a command that sets the logging channel?
# --- Ticket Open ---
#client.command()
#commands.guild_only()
async def ticket(ctx):
if ctx.channel.type != discord.ChannelType.private:
channels = [str(channel) for channel in client.get_all_channels()]
if f'ticket-{ctx.author.id}' in channels:
await ctx.message.delete()
else:
ticket_channel = await ctx.guild.create_text_channel(f'ticket-{ctx.author.id}')
await ticket_channel.set_permissions(ctx.guild.default_role, send_messages=False, read_messages=False)
await ticket_channel.set_permissions(ctx.author, send_messages=True, read_messages=True, add_reactions=True, embed_links=True, attach_files=True, read_message_history=True, external_emojis=True)
embed = discord.Embed(color=10181046, description=f'Please enter the reason for this ticket, type `-close` if you want to close this ticket.')
embed.set_thumbnail(url='')
await ticket_channel.send(f'{ctx.author.mention}', embed=embed)
await ctx.message.delete()
logchannel = await client.fetch_channel('850364625479532545')
embed = discord.Embed(title="Ticket Created",
description="",
color=discord.Colour.green())
embed.add_field(name=f'**By:** {ctx.author}',value= f'**ID:** {ctx.author.id}')
await logchannel.send(embed=embed)
#--- Ticket Close ---
#client.command()
#commands.guild_only()
async def close(ctx):
print(f'{ctx.author} | {ctx.author.id} -> {client.command_prefix}close')
if ctx.channel.type != discord.ChannelType.private:
admin_roles = [834126146215477348,835608325273157733,838859643224326144,835582821221138472,835914273402126376]
if ctx.channel.name == f'ticket-{ctx.author.id}':
await ctx.channel.delete()
elif admin_roles and 'ticket' in ctx.channel.name or ctx.author.id in administrator_ids and 'ticket' in ctx.channel.name:
await ctx.channel.delete()
else:
await ctx.message.delete()
logchannel = await client.fetch_channel('850364625479532545')
embed = discord.Embed(title="Ticket Closed",
description="",
color=discord.Colour.red())
embed.add_field(name=f'**By:** {ctx.author}',value= f'**ID:** {ctx.author.id}')
await logchannel.send(embed=embed)
Tip: if you want to create a public bot don't use handwritten channel id, you'd better save to file for all servers in json file and set it with command.
For example this:
{
"server identifier": "system channel identifier",
...
}
I don't know what's wrong with the code.
I've got on_member_joion and on_member_leave code, and it's not working, this is my code:
intents = discord.Intents.default()
intents.members = True
botprefix = ","
bot = commands.Bot(command_prefix = botprefix, case_insensitive=True, intents = intents)
#bot.event
async def on_mmember_join(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f"Witaj {member.mention} na serwerze **Pogaduszki!**")
#bot.event
async def on_member_leave(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f"Żegnamy {member.mention}, mamy nadzieję że do nas wrócisz")
And this code is not working, there are no errors, can anyone help please??
PS: I'm using https://replit.com
You have an error with your join event.
It should be on_member_join and not on_mmember_join.
Also, you should consider not using on_member_leave but on_member_remove.
Your full code:
#bot.event
async def on_member_join(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f "Witaj {member.mention} na serwerze **Pogaduszki!**")
#bot.event
async def on_member_remove(member):
channel = bot.get_channel(803616331835899934)
await channel.send(f "Żegnamy {member.mention}, mamy nadzieję że do nas wrócisz")
Also have a look at the docs for more:
on_member_remove()
I'm trying to add a few subcommands to my code to make everything clearer.
Unfortunately, I have the problem that certain sections of code are simply not executed.
My Code:
#commands.group(invoke_without_command=True)
async def server(self, ctx):
created = ctx.guild.created_at
x = re.search("^.*:", str(created))
x = x.group()
x = x[:-6]
me = ctx.guild
embed = discord.Embed(title = f"Information about ``{ctx.guild}``", description=me.description, color = 0xf7fcfd, timestamp=ctx.message.created_at)
embed.add_field(name="__Information__", value=f"**Owner:** {me.owner}\n**Name:** {me.name}\n**ID:** {me.id}\n**Region:** {me.region}\n**Created at:** {x}", inline=False)
embed.add_field(name="__Server Information__", value=f"**Member**: {len(me.members)}\n**Roles:** {len(me.roles)}\n**Max Emojis:** {me.emoji_limit}\n**Emojis:** {len(me.emojis)}", inline=False)
embed.add_field(name="__Channel Information__", value=f"**Text-Channel:** {str(len(me.text_channels))}\n**Voice-Channel:** {str(len(me.voice_channels))}\n**AFK-Channel:** ``{me.afk_channel}``\n**AFK-Timeout:** ``{me.afk_timeout}sec``")
embed.set_footer(text=f"{ctx.message.author.name}", icon_url=ctx.message.author.avatar_url)
embed.set_thumbnail(url=me.icon_url)
embed.set_image(url=me.banner_url)
await ctx.send(embed=embed)
# SERVER AVATAR
#server.command()
async def avatar(self, ctx):
if not ctx.guild.icon:
embed = discord.Embed(title="Server has no avatar!", color=0xf7fcfd)
return await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f"Avatar of {ctx.guild.name}", color=0xf7fcfd)
embed.set_image(url=ctx.guild.icon_url_as(size=1024))
await ctx.send(embed=embed)
# SERVER BANNER
#server.command()
async def banner(self, ctx):
if not ctx.guild.banner:
embed = discord.Embed(title="Server has no banner!", color=0xf7fcfd)
return await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f"Banner of {ctx.guild.name}", color=0xf7fcfd)
embed.set_image(url=ctx.guild.banner_url_as(format='png'))
await ctx.send(embed=embed)
The problem is that the command ?server avatar does not provide any output. The commands ?server and ?server banner work perfectly.
Am I using the subcommands incorrectly or why do I get no output?
The reason why it didn't work is that I already had another command called avatar. The Bot would always take the command (avatar) instead the subcommand (server avatar).
I have got an error: TypeError: on_message() missing 1 required positional argument: 'member'
How do I fix this error and what do I have to do with it?
Here is my code:
import discord
import config
client = discord.Client()
#client.event
async def on_message(message, member):
id = client.get_guild(config.ID) # ID в файле config
channels = [
647074685535649802,
636901028478058497,
690272147050070158,
694196995887202375,
690276595578962177,
654662320735387648,
650381379892412426,
641704849196711976,
]
badwords = ["лузер", "расизм", "нацизм"]
valid_users = ["Resadesker#1103"]
unwarnusers = ["ResadeskerBOT#7104"]
if str(message.author) in valid_users:
for channelo in channels:
if message.content[:message.content.find(' ')] == "$spam":
channel = client.get_channel(channelo)
await channel.send(message.content[message.content.find(' '):])
for word in badwords:
if word in message.content.lower():
if str(message.author) != "ResadeskerBOT#7104":
warnFile = open("D:/python/disbot/warns.txt", "a")
warnFile.write(str(message.author) + "\n")
warnFile.close()
mutedRole = discord.utils.get(message.guild.roles, name='JB-MUTED')
await member.add_roles(mutedRole)
channel = client.get_channel(696315924591935488)
await channel.send(f"--------------------\nЗа человеком {message.author.mention} было замечено нарушение. \nВот его сообщение: \n{message.content} \nНарушение было в канале {message.channel}\n--------------------")
client.run(config.TOKEN)
You are using old code from before the discord.py rewrite but running a newer version.
Just change your:
#client.event
async def on_message(message, member):
to
#client.event
async def on_message(message):
And it should work.