Im trying make the bot count to whatever the user says but it is not sending anything
#commands.cooldown(1, 5, commands.BucketType.user)
#client.command()
async def count(ctx, num):
for i in range(1, num+1):
await ctx.channel.send(i)
There is no error.
Can anyone help
The problem is that num has to be an integer. Here's how you should do it :-
#client.command()
async def count(ctx, num: int):
for i in range(1, num+1):
await ctx.send(i)
Related
I’m trying to code a simple music bot for discord in python. I tried coding a queue command so that I can queue a certain song (searching for songs and playing them etc. all work). This is my code for the queue command:
#commands.command()
async def checkqueue(self, ctx):
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("Queue is empty")
else:
embed = discord.Embed(title="Song Queue", description="", colour=discord.colour.dark_gold())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
await ctx.send(embed=embed)
When the queue is empty, the bot sends a message in discord saying "Queue is empty”. When I use the play command, it adds a song to the queue. However, when I try to use the checkqueue command when there’s at least one song in the queue, the bot doesn’t send the embed. Not sure if this is a problem with the code in the queue command or outside the queue command, so here’s the cut-down version of the rest of my code in my commands Cog.
import discord
from discord.ext import commands
import youtube_dl
import pafy
import asyncio
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
self.song_queue = {}
#commands.Cog.listener()
async def on_ready(self):
for guild in self.client.guilds:
self.song_queue[guild.id] = []
async def check_queue(self, ctx):
if len(self.song_queue[ctx.guild.id]) > 0:
ctx.voice_client.stop()
await self.play_song(ctx, self.song_queue[ctx.guild.id][0])
self.song_queue[ctx.guild.id].pop(0)
async def search_song(self, amount, song, get_url=False):
info = await self.client.loop.run_in_executor(None, lambda: youtube_dl.YoutubeDL({"format": "bestaudio", "quiet" : True}).extract_info(f"ytsearch{amount}:{song}", download=False, ie_key="YoutubeSearch"))
if len(info["entries"]) == 0:
return None
return [entry["webpage_url"] for entry in info["entries"]] if get_url else info
async def play_song(self, ctx, song):
url = pafy.new(song).getbestaudio().url
ctx.voice_client.play(discord.PCMVolumeTransformer(discord.FFmpegPCMAudio(url)), after=lambda error: self.client.loop.create_task(self.check_queue(ctx)))
ctx.voice_client.source.volume = 0.5
#commands.command()
async def stop(self, ctx):
if ctx.voice_client is not None:
return await ctx.voice_client.disconnect()
return await ctx.send("Disconnected")
else:
return await ctx.send("I am not connected to a voice channel")
#commands.command()
async def join(self, ctx):
if ctx.author.voice is None:
return await ctx.send("You are not connected to a voice channel")
else:
channel = ctx.author.voice.channel
await channel.connect()
await ctx.send(f"Connected to voice channel: '{channel}'")
#commands.command()
async def play(self, ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to play.")
if ctx.voice_client is None:
return await ctx.send("I must be in a voice channel to play a song.")
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for a song, this may take a few seconds...")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I couldn't find the song you asked for. Try using my search command to find the song you want.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"Song added to the queue at position {queue_len+1}")
else:
return await ctx.send("Maximum queue limit has been reached, please wait for the current song to end to add more songs to the queue")
await self.play_song(ctx, song)
await ctx.send(f"Now playing: {song}")
#commands.command()
async def search(self, ctx, *, song=None):
if song is None:
return await ctx.send("Please include a song to search for")
await ctx.send("Searching for song, this may take a few seconds...")
info = await self.search_song(5, song)
embed = discord.Embed(title=f"Results for '{song}':", description="You can use these URL's to play the song\n", colour=discord.Colour.blue())
amount = 0
for entry in info["entries"]:
embed.description += f"[{entry['title']}]({entry['webpage_url']})\n"
amount += 1
embed.set_footer(text=f"Displaying the first {amount} results.")
await ctx.send(embed=embed)
#commands.command()
async def checkqueue(self, ctx):
if len(self.song_queue[ctx.guild.id]) == 0:
return await ctx.send("Queue is empty")
else:
embed = discord.Embed(title="Song Queue", description="", colour=discord.colour.blue())
i = 1
for url in self.song_queue[ctx.guild.id]:
embed.description += f"{i}) {url}\n"
i += 1
await ctx.send(embed=embed)
#commands.command()
async def queue(self, ctx, *, song=None):
if song is None:
return await ctx.send("You must include a song to queue.")
if not ("youtube.com/watch?" in song or "https://youtu.be/" in song):
await ctx.send("Searching for a song, this may take a few seconds...")
result = await self.search_song(1, song, get_url=True)
if result is None:
return await ctx.send("Sorry, I couldn't find the song you asked for. Try using my search command to find the song you want.")
song = result[0]
if ctx.voice_client.source is not None:
queue_len = len(self.song_queue[ctx.guild.id])
if queue_len < 10:
self.song_queue[ctx.guild.id].append(song)
return await ctx.send(f"Song added to the queue at position {queue_len+1}")
else:
return await ctx.send("Maximum queue limit has been reached, please wait for the current song to end to add more songs to the queue")
The issue that I was having with your code was the color of the Embed. Everything else went smoothly when I ran your code. When you referenced the Colour, you didn't properly access the function.
What you did:
embed = discord.Embed(title="Song Queue",
description="",
colour=discord.colour.dark_gold())
What you should do:
embed = discord.Embed(title="Song Queue",
description="",
colour=discord.Colour.dark_gold())
I starting to learning discord.py and I got some idea to make a anti advertising link function. My plan is detect a link that have http or https in link they send and give they a role and in my plan this role name is gg and this is my code
#Advertising link detection
#client.event
async def on_message(message):
if 'https' in message.content.lower():
await message.delete()
await message.channel.send(f"{message.author.mention} This link not ALLOWED")
else:
await client.process_commands(message)
#client.event
async def on_message(message):
if 'http' in message.content.lower():
await message.delete()
await message.channel.send(f"{message.author.mention} This link not ALLOWED")
else:
await client.process_commands(message)
#autorole
autorole = discord.utils.get(ctx.guild.roles, name='gg')
await ctx.add.roles(autorole)
I really no idea how to do this function
So in your code you have two functions with the same name, so the second one overrides the first one and only the second one is used and the first one is discarded. Most of the time situations like this can be avoided by using a single event with the code combined. in your case that would work too using a elif or the or keyword. so
#client.event
async def on_message(message):
if 'https' in message.content.lower() or 'http' in message.content.lower():
await message.delete()
await message.channel.send(f"{message.author.mention} This link not ALLOWED")
else:
await client.process_commands(message)
but I would highly suggest using regex to match for urls
You have called same event 2 times and that causes bot to stuck use else if two add 2 if statement
You have 2 events
on_message(message):
How To Make Discord.py dev only Commands
def restart_bot():
os.execv(sys.executable, ['python'] + sys.argv)
#Bot.command(name= 'restart')
async def restart(ctx):
await ctx.send("Restarting bot...")
restart_bot()
You can do with #commands.is_owner()
basically like this:
#Bot.command(name = 'restart')
#commands.is_owner()
async def restart(ctx):
await ctx.send("Restarting bot...")
restart_bot()
thank me later :D
I want it to say the same file again when using the command again but it doesn't work please help
#client.command()
async def join(ctx):
voicechannel = discord.utils.get(ctx.guild.channels, name='text')
vc = await voicechannel.connect()
vc.play(discord.FFmpegPCMAudio('deneme/audio.mp3'), after=lambda e: print('done', e))
I would like to, as an admin, add points to a specific member's balance
Know how to create a JSON file with all the "points" someone has.
import discord
from discord.ext import commands
import random
import os
import json
# this line of code gives the bot a comand prefix
bot = commands.Bot(command_prefix="/")
# This line of code tells the bot to start up
#bot.event
async def on_ready():
print("The bot is now online!")
#bot.command(pass_context=True)
async def leaderboard(ctx):
await ctx.send("This is a work in progress, this will dieplay the leaderboard")
amounts = {}
#bot.command(pass_context=True)
async def balance(ctx):
id = str(ctx.message.author.id)
if id in amounts:
await ctx.send("You have {} ben points".format(amounts[id]))
else:
await ctx.send("You do not have an account")
#bot.command(pass_context=True)
async def register(ctx):
id = str(ctx.message.author.id)
if id not in amounts.keys:
amounts[id] = 100
await ctx.send("You are now registered")
_save()
else:
await ctx.send("You already have an account")
#bot.command(pass_context=True)
async def transfer(ctx, amount: int, other: discord.Member):
primary_id = str(ctx.message.author.id)
other_id = str(other.id)
if primary_id not in amounts:
await ctx.send("You do not have an account")
elif other_id not in amounts:
await ctx.send("The other party does not have an account")
elif amounts[primary_id] < amount:
await ctx.send("You cannot afford this transaction")
else:
amounts[primary_id] -= amount
amounts[other_id] += amount
await ctx.send("Transaction complete")
_save()
def _save():
with open('amounts.json', 'w+') as f:
json.dump(amounts, f)
#bot.command()
async def save():
_save()
#This line of code tells the bot to run
bot.run("Token")
I am not sure on what I am meant to do from here.
I might be over complicating the code if anyone can make it more efficient I will be incredibly grateful.
Here's the essential usage and everything you'll need to know for the basics of JSON:
# Creating a dictionary with some values
>>> data = {"foo": "bar", "key": "value"}
# Opening a file and writing to it
>>> with open("db.json", "w+") as fp:
... json.dump(data, fp, sort_keys=True, indent=4) # Kwargs for beautification
# Loading in data from a file
>>> with open("db.json", "r") as fp:
... data = json.load(fp)
# Accessing the values
>>> data["foo"]
'bar'
>>> data["key"]
'value'
This can be adapted to suit your needs, perhaps something like:
# Let's say the JSON has the following structure:
# {"users": {112233445566778899: {"points": 0}, 224466881133557799: {"points": 0}}}
# The "users" key is a bit redundant if you're only gonna store users in the file.
# It's down to what you'll be storing in the file and readability etc.
import json
import random
import typing
def add_points(member_id: str, amount: int):
# Open the file first as to load in all the users' data
# Making a new dict would just overwrite the current file's contents
with open("file.json", "r") as fp:
data = json.load(fp)
data["users"][member_id]["points"] += amount
# Write the updated data to the file
with open("file.json", "w+") as fp:
json.dump(data, fp, sort_keys=True, indent=4)
return data["users"][user_id]["points"]
#bot.command()
async def give(ctx, member: typing.Optional[discord.Member]=None, points:typing.Optional[int]=None):
if not member:
member = ctx.author
if not points:
points = random.randint(10, 50)
# Have a separate getter for the points - this was just for the sake of concise code
total_points = add_points(member.id, points)
await ctx.send(f"Successfully gave {member.mention} {points} points! Total: {total_points}")
I'll be happy to clarify anything if need be.
References:
Dictionary exercises - Might be worth taking a look into so then you're comfortable with how they work.
f-Strings - Python 3.6.0+
json.load()
json.dump()
typing.Optional
User.id
commands.Context
Context.author