Discord py - menu with variables from a dictionary - python

I'm trying to create a command that outputs five different memes with the help of a menu. You should then be able to go back and forth with the arrow keys.
Like this, but with arrow buttons below.
So far I have saved the variables for creating the meme in a dictionary. But I don't know how to call it up so that the menu understands it correctly.
My Code:
import discord
import aiohttp
from discord.ext import commands, menus
class Test:
def __init__(self, key, value):
self.key = key
self.value = value
class Source(menus.GroupByPageSource):
async def format_page(self, menu, entry):
offset = ((menu.current_page) * 5) + 1
joined = '\n'.join(f'• ``{v.value}``' for i, v in enumerate(entry.items, offset))
embed = discord.Embed(title=entry.key, description=joined, color=0xf7fcfd)
embed.set_author(name=f"Page: {menu.current_page + 1}/{self.get_max_pages()}")
return embed
class Reddit(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def info(self, ctx):
async with aiohttp.ClientSession() as session:
async with session.get("https://meme-api.herokuapp.com/gimme/5") as resp:
memes = await resp.json()
all_memes = {}
count = 0
for meme in memes["memes"]:
count += 1
await ctx.trigger_typing()
if meme["nsfw"] == True:
return True
all_memes[count] = {
"link": meme["postLink"],
"reddit": meme["subreddit"],
"title": meme["title"],
"author": meme["author"],
"upvotes": meme["ups"],
"nsfw": meme["nsfw"],
"image": meme["preview"][-1]
}
data = [
Test(key=key, value=value)
for key in ["NONE"]
for value in all_memes.values()
]
pages = menus.MenuPages(
source=Source(data, key=lambda t: t.key, per_page=1),
clear_reactions_after=True
)
return await pages.start(ctx)
def setup(client):
client.add_cog(Reddit(client))
If I call the command now, the output looks like this:
It should create an embed like this:
embed = discord.Embed(description=f"[{title}]({link})", color=0xf7fcfd)
embed.set_author(name=f'u/{reddit}')
embed.add_field(name="Author:", value=author)
embed.add_field(name="Upvotes:", value=upvotes)
embed.set_image(url=image)
embed.set_footer(
text=f"Requested by {ctx.author} | Response time : {round(self.client.latency * 1000)} ms",
icon_url=ctx.author.avatar_url,
)
await ctx.send(embed=embed)
Thank you for your time :)

class DisplayPages(Menu):
def __init__(self, pages, timeout: int = 180):
super().__init__(timeout=timeout, clear_reactions_after=True)
self.current = 0
self.pages = pages
async def send_initial_message(self, _, destination):
current = self.pages[self.current]
if isinstance(current, discord.Embed):
return await destination.send(embed=current)
return await destination.send(current)
async def update_index(self, payload, index_change):
self.current = max(0, min(len(self.pages) - 1, self.current + index_change))
async def on_reaction(self, payload, index_change):
await self.update_index(payload, index_change)
current = self.pages[self.current]
if isinstance(current, discord.Embed):
return await self.message.edit(content=None, embed=current)
await self.message.edit(content=current, embed=None)
#menus.button(Reacts.REWIND)
async def go_first(self, payload):
await self.on_reaction(payload, -self.current)
#menus.button(Reacts.ARROW_LEFT)
async def go_prev(self, payload):
await self.on_reaction(payload, -1)
#menus.button(Reacts.ARROW_RIGHT)
async def go_next(self, payload):
await self.on_reaction(payload, 1)
#menus.button(Reacts.FAST_FORWARD)
async def go_last(self, payload):
await self.on_reaction(payload, len(self.pages) - self.current - 1)
This is my old base class for menus with 4 buttons for what you want. Works quite simply by editing the message after each button press with a new embed/message.

You can use the AutoEmbedPaginator or CustomEmbedPaginator class of DiscordUtils

Related

Discord.py Command to add and ban words into a db

So I'm wanting to be able to do a command that will add a word to a json file attached to the server id. I have the json file and it storing the server id and name and then loading what is in the json file but I can't seem to add any words to it using a command. Any ideas?
async def open_bword(guild):
guilds = await get_bword_data()
if str(guild.id) in guilds:
return False
else:
guilds[str(guild.id)] = {}
guilds[str(guild.id)][str(guild)] = {}
guilds[str(guild.id)]["Banned Words"] = 0
with open('banwords.json','w') as f:
json.dump(guilds,f)
return True
async def get_bword_data():
with open('banwords.json','r') as f:
guilds = json.load(f)
return guilds
async def update_bword(guild,change=0,mode = 'Banned Words'):
guilds = await get_bword_data()
guilds[str(guild.id)][mode] += change
with open('banwords.json','w') as f:
json.dump(guilds,f)
list = guilds[str(guild.id)]['Banned Words']
return list
class Banwords(commands.Cog):
def __init__(self, client):
self.client = client
#commands.Cog.listener()
async def on_ready(self):
print('Banwords cog working')
#commands.command(aliases=['list'])
async def banlist(self, ctx):
await open_bword(ctx.guild)
guild = ctx.guild
guilds = await get_bword_data()
bannedwords_list = guilds[str(guild.id)]["Banned Words"]
em = discord.Embed(title=f'{guild}',color = RandomColor())
em.add_field(name="banned words", value=bannedwords_list)
await ctx.send(embed= em)

discord.py - edit the interaction message after a timeout in discord.ui.Select

How can I access the interaction message and edit it?
discord.ui.Select
class SearchMenu(discord.ui.Select):
def __init__(self, ctx, bot, data):
self.ctx = ctx
self.bot = bot
self.data = data
self.player = Player
values = []
for index, track in enumerate(self.data[:9]):
values.append(
discord.SelectOption(
label=track.title,
value=index + 1,
description=track.author,
emoji=f"{index + 1}\U0000fe0f\U000020e3"
)
)
values.append(discord.SelectOption(label='Cancel', description='Exit the search menu.', emoji="🔒"))
super().__init__(placeholder='Click on the Dropdown.', min_values=1, max_values=1, options=values)
async def callback(self, interaction: discord.Interaction):
if self.values[0] == "Cancel":
embed = Embed(emoji=self.ctx.emoji.whitecheck, description="This interaction has been deleted.")
return await interaction.message.edit(embed=embed, view=None)
discord.ui.View
class SearchMenuView(discord.ui.View):
def __init__(self, options, ctx, bot):
super().__init__(timeout=60.0)
self.ctx = ctx
self.add_item(SearchMenu(ctx, bot, options))
async def interaction_check(self, interaction: discord.Interaction):
if interaction.user != self.ctx.author:
embed = Embed(description=f"Sorry, but this interaction can only be used by {self.ctx.author.name}.")
await interaction.response.send_message(embed=embed, ephemeral=True)
return False
else:
return True
async def on_timeout(self):
embed = Embed(emoji=self.ctx.emoji.whitecross, description="Interaction has timed out. Please try again.")
await self.message.edit(embed=embed, view=None)
If I try to edit the interaction like this I am getting
-> AttributeError: 'SearchMenuView' object has no attribute 'message'
After 60 seconds the original message should be replaced with the embed in the timeout.
You're trying to ask the View to send a message, which is not a method in discord.ui.View.
You could defer the response and don't let it timeout and allow the user to try again?
async def interaction_check(self, interaction: discord.Interaction):
if interaction.user != self.ctx.author:
embed = Embed(description=f"Sorry, but this interaction can only be used by {self.ctx.author.name}.")
await interaction.channel.send(embed=embed, delete_after=60)
await interaction.response.defer()
return True
view = MyView()
view.message = await channel.send('...', view=view)
After that you can use self.message in on_timeout (or somewhere else you don't have access to interaction.message) to edit it.
Source: https://discord.com/channels/336642139381301249/669155775700271126/860883838657495040

How can I make a discord.py bot not require a prefix?

basically I am making a discord.py music bot, but I don't want to have to type a prefix before every command. I want to make one channel that can use the commands without a prefix beforehand; for example, instead of saying music.play in the channel, I just want to be able to say "play __". Is this possible? I also would like to figure out how to delete the message with the command, so for example you say "play __" and then as soon as that happens the bot deletes the message that said that and just does what it's supposed to. This would make the whole thing a lot cleaner and easier to use.
however, this isn't limited to specifically music bots, I'm also wondering in general how to create a specific channel you don't have to use a bot's prefix for.
Thanks for the help!
my code is as follows:
import asyncio
import functools
import itertools
import math
import random
import os
import discord
import youtube_dl
from async_timeout import timeout
from discord.ext import commands
# Silence useless bug reports messages
youtube_dl.utils.bug_reports_message = lambda: ''
class VoiceError(Exception):
pass
class YTDLError(Exception):
pass
class YTDLSource(discord.PCMVolumeTransformer):
YTDL_OPTIONS = {
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': 'mp3',
'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
'restrictfilenames': True,
'noplaylist': True,
'nocheckcertificate': True,
'ignoreerrors': False,
'logtostderr': False,
'quiet': True,
'no_warnings': True,
'default_search': 'auto',
'source_address': '0.0.0.0',
}
FFMPEG_OPTIONS = {
'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
'options': '-vn',
}
ytdl = youtube_dl.YoutubeDL(YTDL_OPTIONS)
def __init__(self, ctx: commands.Context, source: discord.FFmpegPCMAudio, *, data: dict, volume: float = 0.5):
super().__init__(source, volume)
self.requester = ctx.author
self.channel = ctx.channel
self.data = data
self.uploader = data.get('uploader')
self.uploader_url = data.get('uploader_url')
date = data.get('upload_date')
self.upload_date = date[6:8] + '.' + date[4:6] + '.' + date[0:4]
self.title = data.get('title')
self.thumbnail = data.get('thumbnail')
self.description = data.get('description')
self.duration = self.parse_duration(int(data.get('duration')))
self.tags = data.get('tags')
self.url = data.get('webpage_url')
self.views = data.get('view_count')
self.likes = data.get('like_count')
self.dislikes = data.get('dislike_count')
self.stream_url = data.get('url')
def __str__(self):
return '**{0.title}** by **{0.uploader}**'.format(self)
#classmethod
async def create_source(cls, ctx: commands.Context, search: str, *, loop: asyncio.BaseEventLoop = None):
loop = loop or asyncio.get_event_loop()
partial = functools.partial(cls.ytdl.extract_info, search, download=False, process=False)
data = await loop.run_in_executor(None, partial)
if data is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
if 'entries' not in data:
process_info = data
else:
process_info = None
for entry in data['entries']:
if entry:
process_info = entry
break
if process_info is None:
raise YTDLError('Couldn\'t find anything that matches `{}`'.format(search))
webpage_url = process_info['webpage_url']
partial = functools.partial(cls.ytdl.extract_info, webpage_url, download=False)
processed_info = await loop.run_in_executor(None, partial)
if processed_info is None:
raise YTDLError('Couldn\'t fetch `{}`'.format(webpage_url))
if 'entries' not in processed_info:
info = processed_info
else:
info = None
while info is None:
try:
info = processed_info['entries'].pop(0)
except IndexError:
raise YTDLError('Couldn\'t retrieve any matches for `{}`'.format(webpage_url))
return cls(ctx, discord.FFmpegPCMAudio(info['url'], **cls.FFMPEG_OPTIONS), data=info)
#staticmethod
def parse_duration(duration: int):
minutes, seconds = divmod(duration, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
duration = []
if days > 0:
duration.append('{} days'.format(days))
if hours > 0:
duration.append('{} hours'.format(hours))
if minutes > 0:
duration.append('{} minutes'.format(minutes))
if seconds > 0:
duration.append('{} seconds'.format(seconds))
return ', '.join(duration)
class Song:
__slots__ = ('source', 'requester')
def __init__(self, source: YTDLSource):
self.source = source
self.requester = source.requester
def create_embed(self):
embed = (discord.Embed(title='Now playing',
description='```css\n{0.source.title}\n```'.format(self),
color=discord.Color.blurple())
.add_field(name='Duration', value=self.source.duration)
.add_field(name='Requested by', value=self.requester.mention)
.add_field(name='Uploader', value='[{0.source.uploader}]({0.source.uploader_url})'.format(self))
.add_field(name='URL', value='[Click]({0.source.url})'.format(self))
.set_thumbnail(url=self.source.thumbnail))
return embed
class SongQueue(asyncio.Queue):
def __getitem__(self, item):
if isinstance(item, slice):
return list(itertools.islice(self._queue, item.start, item.stop, item.step))
else:
return self._queue[item]
def __iter__(self):
return self._queue.__iter__()
def __len__(self):
return self.qsize()
def clear(self):
self._queue.clear()
def shuffle(self):
random.shuffle(self._queue)
def remove(self, index: int):
del self._queue[index]
class VoiceState:
def __init__(self, bot: commands.Bot, ctx: commands.Context):
self.bot = bot
self._ctx = ctx
self.current = None
self.voice = None
self.next = asyncio.Event()
self.songs = SongQueue()
self._loop = False
self._volume = 0.5
self.skip_votes = set()
self.audio_player = bot.loop.create_task(self.audio_player_task())
def __del__(self):
self.audio_player.cancel()
#property
def loop(self):
return self._loop
#loop.setter
def loop(self, value: bool):
self._loop = value
#property
def volume(self):
return self._volume
#volume.setter
def volume(self, value: float):
self._volume = value
#property
def is_playing(self):
return self.voice and self.current
async def audio_player_task(self):
while True:
self.next.clear()
if not self.loop:
# Try to get the next song within 3 minutes.
# If no song will be added to the queue in time,
# the player will disconnect due to performance
# reasons.
try:
async with timeout(180): # 3 minutes
self.current = await self.songs.get()
except asyncio.TimeoutError:
self.bot.loop.create_task(self.stop())
return
self.current.source.volume = self._volume
self.voice.play(self.current.source, after=self.play_next_song)
await self.current.source.channel.send(embed=self.current.create_embed())
await self.next.wait()
def play_next_song(self, error=None):
if error:
raise VoiceError(str(error))
self.next.set()
def skip(self):
self.skip_votes.clear()
if self.is_playing:
self.voice.stop()
async def stop(self):
self.songs.clear()
if self.voice:
await self.voice.disconnect()
self.voice = None
class Music(commands.Cog):
def __init__(self, bot: commands.Bot):
self.bot = bot
self.voice_states = {}
def get_voice_state(self, ctx: commands.Context):
state = self.voice_states.get(ctx.guild.id)
if not state:
state = VoiceState(self.bot, ctx)
self.voice_states[ctx.guild.id] = state
return state
def cog_unload(self):
for state in self.voice_states.values():
self.bot.loop.create_task(state.stop())
def cog_check(self, ctx: commands.Context):
if not ctx.guild:
raise commands.NoPrivateMessage('This command can\'t be used in DM channels.')
return True
async def cog_before_invoke(self, ctx: commands.Context):
ctx.voice_state = self.get_voice_state(ctx)
async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
await ctx.send('An error occurred: {}'.format(str(error)))
#commands.command(name='join', invoke_without_subcommand=True)
async def _join(self, ctx: commands.Context):
"""Joins a voice channel."""
destination = ctx.author.voice.channel
if ctx.voice_state.voice:
await ctx.voice_state.voice.move_to(destination)
return
ctx.voice_state.voice = await destination.connect()
#commands.command(name='summon')
#commands.has_permissions(manage_guild=True)
async def _summon(self, ctx: commands.Context, *, channel: discord.VoiceChannel = None):
"""Summons the bot to a voice channel.
If no channel was specified, it joins your channel.
"""
if not channel and not ctx.author.voice:
raise VoiceError('You are neither connected to a voice channel nor specified a channel to join.')
destination = channel or ctx.author.voice.channel
if ctx.voice_state.voice:
await ctx.voice_state.voice.move_to(destination)
return
ctx.voice_state.voice = await destination.connect()
#commands.command(name='leave', aliases=['disconnect'])
#commands.has_permissions(manage_guild=True)
async def _leave(self, ctx: commands.Context):
"""Clears the queue and leaves the voice channel."""
if not ctx.voice_state.voice:
return await ctx.send('Not connected to any voice channel.')
await ctx.voice_state.stop()
del self.voice_states[ctx.guild.id]
#commands.command(name='volume')
async def _volume(self, ctx: commands.Context, *, volume: int):
"""Sets the volume of the player."""
if not ctx.voice_state.is_playing:
return await ctx.send('Nothing being played at the moment.')
if 0 > volume > 100:
return await ctx.send('Volume must be between 0 and 100')
ctx.voice_state.volume = volume / 100
await ctx.send('Volume of the player set to {}%'.format(volume))
#commands.command(name='now', aliases=['current', 'playing'])
async def _now(self, ctx: commands.Context):
"""Displays the currently playing song."""
await ctx.send(embed=ctx.voice_state.current.create_embed())
#commands.command(name='pause')
#commands.has_permissions(manage_guild=True)
async def _pause(self, ctx: commands.Context):
"""Pauses the currently playing song."""
if ctx.voice_state.is_playing and ctx.voice_state.voice.is_playing():
ctx.voice_state.voice.pause()
await ctx.message.add_reaction('⏯')
#commands.command(name='resume')
#commands.has_permissions(manage_guild=True)
async def _resume(self, ctx: commands.Context):
"""Resumes a currently paused song."""
if ctx.voice_state.is_playing and ctx.voice_state.voice.is_paused():
ctx.voice_state.voice.resume()
await ctx.message.add_reaction('⏯')
#commands.command(name='stop')
#commands.has_permissions(manage_guild=True)
async def _stop(self, ctx: commands.Context):
"""Stops playing song and clears the queue."""
ctx.voice_state.songs.clear()
if ctx.voice_state.is_playing:
ctx.voice_state.voice.stop()
await ctx.message.add_reaction('⏹')
#commands.command(name='skip')
async def _skip(self, ctx: commands.Context):
"""Vote to skip a song. The requester can automatically skip.
3 skip votes are needed for the song to be skipped.
"""
if not ctx.voice_state.is_playing:
return await ctx.send('Not playing any music right now...')
voter = ctx.message.author
if voter == ctx.voice_state.current.requester:
await ctx.message.add_reaction('⏭')
ctx.voice_state.skip()
elif voter.id not in ctx.voice_state.skip_votes:
ctx.voice_state.skip_votes.add(voter.id)
total_votes = len(ctx.voice_state.skip_votes)
if total_votes >= 3:
await ctx.message.add_reaction('⏭')
ctx.voice_state.skip()
else:
await ctx.send('Skip vote added, currently at **{}/3**'.format(total_votes))
else:
await ctx.send('You have already voted to skip this song.')
#commands.command(name='queue')
async def _queue(self, ctx: commands.Context, *, page: int = 1):
"""Shows the player's queue.
You can optionally specify the page to show. Each page contains 10 elements.
"""
if len(ctx.voice_state.songs) == 0:
return await ctx.send('Empty queue.')
items_per_page = 10
pages = math.ceil(len(ctx.voice_state.songs) / items_per_page)
start = (page - 1) * items_per_page
end = start + items_per_page
queue = ''
for i, song in enumerate(ctx.voice_state.songs[start:end], start=start):
queue += '`{0}.` [**{1.source.title}**]({1.source.url})\n'.format(i + 1, song)
embed = (discord.Embed(description='**{} tracks:**\n\n{}'.format(len(ctx.voice_state.songs), queue))
.set_footer(text='Viewing page {}/{}'.format(page, pages)))
await ctx.send(embed=embed)
#commands.command(name='shuffle')
async def _shuffle(self, ctx: commands.Context):
"""Shuffles the queue."""
if len(ctx.voice_state.songs) == 0:
return await ctx.send('Empty queue.')
ctx.voice_state.songs.shuffle()
await ctx.message.add_reaction('✅')
#commands.command(name='remove')
async def _remove(self, ctx: commands.Context, index: int):
"""Removes a song from the queue at a given index."""
if len(ctx.voice_state.songs) == 0:
return await ctx.send('Empty queue.')
ctx.voice_state.songs.remove(index - 1)
await ctx.message.add_reaction('✅')
#commands.command(name='loop')
async def _loop(self, ctx: commands.Context):
"""Loops the currently playing song.
Invoke this command again to unloop the song.
"""
if not ctx.voice_state.is_playing:
return await ctx.send('Nothing being played at the moment.')
# Inverse boolean value to loop and unloop.
ctx.voice_state.loop = not ctx.voice_state.loop
await ctx.message.add_reaction('✅')
#commands.command(name='play')
async def _play(self, ctx: commands.Context, *, search: str):
"""Plays a song.
If there are songs in the queue, this will be queued until the
other songs finished playing.
This command automatically searches from various sites if no URL is provided.
A list of these sites can be found here: https://rg3.github.io/youtube-dl/supportedsites.html
"""
if not ctx.voice_state.voice:
await ctx.invoke(self._join)
async with ctx.typing():
try:
source = await YTDLSource.create_source(ctx, search, loop=self.bot.loop)
except YTDLError as e:
await ctx.send('An error occurred while processing this request: {}'.format(str(e)))
else:
song = Song(source)
await ctx.voice_state.songs.put(song)
await ctx.send('Enqueued {}'.format(str(source)))
#_join.before_invoke
#_play.before_invoke
async def ensure_voice_state(self, ctx: commands.Context):
if not ctx.author.voice or not ctx.author.voice.channel:
raise commands.CommandError('You are not connected to any voice channel.')
if ctx.voice_client:
if ctx.voice_client.channel != ctx.author.voice.channel:
raise commands.CommandError('Bot is already in a voice channel.')
bot = commands.Bot('music.', description='Yet another music bot.')
bot.add_cog(Music(bot))
#bot.event
async def on_ready():
print('Logged in as:\n{0.user.name}\n{0.user.id}'.format(bot))
bot.run(os.getenv("TOKEN"))
I am running this on repl.it, so keep_alive is a file to make the bot be pinged every so often so it doesn't go offline, and importing os and using .env files is a way to keep private data (like my bot token) away from anyone seeing them.
Since i can't reply to your comment on answer 1, here you go, i think this is what you want.
If you want the prefix to be none in only one channel, you could make a function to check if the channel equals the channel where you dont need the prefix.
def get_prefix(bot, message):
if message.channel.id == CHANNEL_WITHOUT_PREFIX_ID:
return ""
else:
return "PREFIX"
bot = commands.Bot(command_prefix=get_prefix, description='Yet another music bot.')
You can do it by leaving empty string
bot = commands.Bot('', description='Yet another music bot.')
I must make your vision clear that if you do so your bot can catch any of the chat also. Therefore, you handle the error that if a word thats not the command of bot should not take it. Otherwise, the bot becomes slow.
You could also just create something like this:
#bot.event
async def on_message(message):
if message.content == 'test':
await message.channel.send('Testing 1 2 3!')

Missing 1 required positional argument: 'number'

Hi I'm having an issue running a asyncio loop it's asking for a missing 1 required positional argument: 'number'.
Here is what I'm working with:
async def purge_modlog(ctx, number):
tomorrow = datetime.now()+timedelta(days=1)
midnight = datetime(year=tomorrow.year, month=tomorrow.month,
day=tomorrow.day, hour=20, minute=35, second=0)
number = int(number)
server = before.server
db = fileIO(self.direct, "load")
if not server.id in db:
return
channel = db[server.id]["Channel"]
if number > 99 or number < 1:
await ctx.send("I can only delete messages within a range of 1 - 99", delete_after=10)
else:
author = ctx.message.author
authorID = author.id
mgs = []
number = int(number)
channel = modlog
async for x in bot.logs_from((channel), limit = int(number+1)):
mgs.append(x)
await asyncio.sleep((midnight - datetime.now()).seconds)
print("Deleting modlog messages 14 day or older")
await asyncio.sleep(5)
await delete_messages(mgs)
await ctx.send('Success!', delete_after=4)
await asyncio.sleep(86400) # Wait 24 hours
def check_folder():
if not os.path.exists('data/modlogset'):
print('Creating data/modlogset folder...')
os.makedirs('data/modlogset')
def check_file():
f = 'data/modlogset/settings.json'
if not fileIO(f, 'check'):
print('Creating default settings.json...')
fileIO(f, 'save', {})
def setup(bot):
check_folder()
check_file()
q = ModLog(bot)
loop = asyncio.get_event_loop()
loop.create_task(q.purge_modlog())
bot.add_cog(q)
To loop the event under def def setup(bot): You can see
loop = asyncio.get_event_loop()
loop.create_task(q.purge_modlog())
This is supposed to loop the event (q.purge_modlog()) I'm not sure what I'm doing wrong here. I have already tried the follow (q.purge_modlog(ctx, number))
line 686, in setup
loop.create_task(q.purge_modlog(ctx, number))
NameError: name 'ctx' is not defined
If anyone could help me that would be great. To add this is a module.
I have corrected some mistakes here. Try to read through the discord.py documentation on purging messages.
class ModLog:
def __init__(self, bot):
self.bot = bot
async def on_ready(self):
await self.bot.wait_until_ready()
for server in self.bot.servers:
channel = self.bot.get_channel("channel ID here")
if channel:
self.bot.loop.create_task(self.modlog_purge(channel))
async def modlog_purge(self, channel):
while True:
now = datetime.utcnow()
two_weeks_ago = now - timedelta(days=14)
await self.bot.purge_from(channel, before=two_weeks_ago)
await asyncio.sleep(86400)
def setup(bot):
q = ModLog(bot)
bot.add_cog(q)
class ModLog:
def __init__(self, bot):
self.bot = bot
async def on_ready(self):
await self.bot.wait_until_ready()
for guild in self.bot.guilds:
channel = await self.get_channel(guild)
if channel:
self.bot.loop.create_task(self.modlog_purge(channel))
async def get_channel(guild):
# Whatever your logic for getting the Channel for a given guild is
async def modlog_purge(self, channel):
while True:
now = datetime.utcnow()
two_weeks_ago = now - timedelta(days=14)
await channel.purge(before=two_weeks_ago)
await asyncio.sleep(86400)
def setup(bot):
q = ModLog(bot)
bot.add_cog(q)
Here's how I would structure this (I'm not on a computer with discord.py at the moment, so there may be some errors). We have an on_ready event that kicks off background tasks for each server that has a channel we want to maintain (this could instead loop through a list of channels, or something similar).
The actual purge is all taken care of by the TextChannel.purge coroutine. We just pass it a datetime object, and it deletes 100 messages from before that date (this is configurable). It then sleeps for a day and repeats.

How do I create a disconnect timer in my python discord music bot?

I have tinkered around a discord music bot cog I got from github. I am stuck at trying to create a timer for the bot to leave a voice channel if the /play command hasn't been executed for 5 minutes. The long code is blow or the pastebin: https://pastebin.com/HPqxW2Nk
Commands are removed. The problem is at line 229.
I tried asyncio.sleep(20) but it leaves 20 secs after even if /play has been executed 15 seconds into the timer.
Please help me solve this problem! Thank you very much!
EDIT: is something like this, Patrick?
async def on_command_completion(self, ctx):
futuretime = datetime.datetime.now() + datetime.timedelta(minutes=5)
await asyncio.sleep(300)
if ctx.invoke(ctx.play):
pass
elif datetime.datetime.now() > futuretime:
await ctx.music_state.stop()
import asyncio
import functools
import logging
import os
import pathlib
import shutil
from asyncio import Queue
import discord
import discord.ext.commands as commands
import youtube_dl
from random import shuffle
def setup(bot):
bot.add_cog(Music(bot))
#bot.loop.create_task(MusicDelete(bot).background_loop())
def duration_to_str(duration):
# Extract minutes, hours and days
minutes, seconds = divmod(duration, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
# Create a fancy string
duration = []
if days > 0: duration.append(f'**{days}** day(s)')
if hours > 0: duration.append(f'**{hours}** hr(s)')
if minutes > 0: duration.append(f'**{minutes}** min(s)')
if seconds > 0 or len(duration) == 0: duration.append(f'**{seconds}** sec(s)')
return ', '.join(duration)
class MusicError(commands.UserInputError):
pass
class Song(discord.PCMVolumeTransformer):
def __init__(self, song_info):
self.info = song_info.info
self.requester = song_info.requester
self.channel = song_info.channel
self.filename = song_info.filename
super().__init__(discord.FFmpegPCMAudio(self.filename, before_options='-nostdin', options='-vn'))
def __str__(self):
return self.info['title']
class SongInfo:
ytdl_opts = {
'default_search': 'auto',
'format': 'bestaudio/best',
'ignoreerrors': True,
'source_address': '0.0.0.0', # Make all connections via IPv4
'nocheckcertificate': True,
'restrictfilenames': True,
'logger': logging.getLogger(__name__),
'logtostderr': False,
'no_warnings': True,
'quiet': True,
'outtmpl': 'C:/Users/MSI/Desktop/GruppBot/musicfiles/%(title)s.%(ext)s',
'noplaylist': True
}
ytdl = youtube_dl.YoutubeDL(ytdl_opts)
def __init__(self, info, requester, channel):
self.info = info
self.requester = requester
self.channel = channel
self.filename = info.get('_filename', self.ytdl.prepare_filename(self.info))
self.downloaded = asyncio.Event()
self.local_file = '_filename' in info
#classmethod
async def create(cls, query, requester, channel, loop=None):
try:
# Path.is_file() can throw a OSError on syntactically incorrect paths, like urls.
if pathlib.Path(query).is_file():
return cls.from_file(query, requester, channel)
except OSError:
pass
return await cls.from_ytdl(query, requester, channel, loop=loop)
#classmethod
def from_file(cls, file, requester, channel):
path = pathlib.Path(file)
if not path.exists():
raise MusicError(f'File {file} not found.')
info = {
'_filename': file,
'title': path.stem,
'creator': 'local file',
}
return cls(info, requester, channel)
#classmethod
async def from_ytdl(cls, request, requester, channel, loop=None):
loop = loop or asyncio.get_event_loop()
# Get sparse info about our query
partial = functools.partial(cls.ytdl.extract_info, request, download=False, process=False)
sparse_info = await loop.run_in_executor(None, partial)
if sparse_info is None:
raise MusicError(f'Could not retrieve info from input : {request}')
# If we get a playlist, select its first valid entry
if "entries" not in sparse_info:
info_to_process = sparse_info
else:
info_to_process = None
for entry in sparse_info['entries']:
if entry is not None:
info_to_process = entry
break
if info_to_process is None:
raise MusicError(f'Could not retrieve info from input : {request}')
# Process full video info
url = info_to_process.get('url', info_to_process.get('webpage_url', info_to_process.get('id')))
partial = functools.partial(cls.ytdl.extract_info, url, download=False)
processed_info = await loop.run_in_executor(None, partial)
if processed_info is None:
raise MusicError(f'Could not retrieve info from input : {request}')
# Select the first search result if any
if "entries" not in processed_info:
info = processed_info
else:
info = None
while info is None:
try:
info = processed_info['entries'].pop(0)
except IndexError:
raise MusicError(f'Could not retrieve info from url : {info_to_process["url"]}')
return cls(info, requester, channel)
async def download(self, loop):
if not pathlib.Path(self.filename).exists():
partial = functools.partial(self.ytdl.extract_info, self.info['webpage_url'], download=True)
self.info = await loop.run_in_executor(None, partial)
self.downloaded.set()
async def wait_until_downloaded(self):
await self.downloaded.wait()
def __str__(self):
title = f"**{self.info['title']}**"
creator = f"**{self.info.get('creator') or self.info['uploader']}**"
duration = f" [ Duration: {duration_to_str(self.info['duration'])} ]" if 'duration' in self.info else ''
return f'{title} from {creator}{duration}'
class Playlist(asyncio.Queue):
def __iter__(self):
return self._queue.__iter__()
def clear(self):
for song in self._queue:
try:
os.remove(song.filename)
except:
pass
self._queue.clear()
def get_song(self):
return self.get_nowait()
def add_song(self, song):
self.put_nowait(song)
def __str__(self):
info = '__**Queued**__:\n'
info_len = len(info)
for song in self:
s = str(song)
l = len(s) + 1 # Counting the extra \n
if info_len + l > 1995:
info += '[...]'
break
info += f'**-** [{s}]({song.info["webpage_url"]})\n'
info_len += l
return info
class GuildMusicState:
def __init__(self, loop):
self.playlist = Playlist(maxsize=10)
self.voice_client = None
self.loop = loop
self.player_volume = 0.5
self.skips = set()
self.min_skips = 3
#property
def current_song(self):
return self.voice_client.source
#property
def volume(self):
return self.player_volume
#volume.setter
def volume(self, value):
self.player_volume = value
if self.voice_client:
self.voice_client.source.volume = value
async def stop(self):
self.playlist.clear()
if self.voice_client:
await self.voice_client.disconnect()
self.voice_client = None
def is_playing(self):
return self.voice_client and self.voice_client.is_playing()
async def play_next_song(self, song=None, error=None):
if error:
await self.current_song.channel.send(f'An error has occurred while playing {self.current_song}: {error}')
if song and not song.local_file and song.filename not in [s.filename for s in self.playlist]:
os.remove(song.filename)
if self.playlist.empty():
await self.stop()
else:
next_song_info = self.playlist.get_song()
await next_song_info.wait_until_downloaded()
source = Song(next_song_info)
source.volume = self.player_volume
self.voice_client.play(source, after=lambda e: asyncio.run_coroutine_threadsafe(self.play_next_song(next_song_info, e), self.loop).result())
embed = discord.Embed(color=0x003366)
embed.set_author(name ="Music", icon_url = 'http://howtodrawdat.com/wp-content/uploads/2014/05/Sebastian-Michaelis-black-butler.png')
embed.add_field(name="Now Playing:", value=f":notes: [{next_song_info}]({self.current_song.info['webpage_url']})", inline=False)
embed.add_field(name="Requested by:", value= self.current_song.requester.mention, inline=False)
#embed.set_thumbnail(url= f"{self.current_song.info['thumbnail']}")
embed.set_footer(text="Type /playlist to see songs in queue.")
await next_song_info.channel.send(embed=embed)
class Music:
def __init__(self, bot):
self.bot = bot
self.music_states = {}
def __unload(self):
for state in self.music_states.values():
self.bot.loop.create_task(state.stop())
def __local_check(self, ctx):
if not ctx.guild:
raise commands.NoPrivateMessage('This command cannot be used in a private message.')
return True
async def __before_invoke(self, ctx):
ctx.music_state = self.get_music_state(ctx.guild.id)
async def __error(self, ctx, error):
if not isinstance(error, commands.UserInputError):
raise error
try:
print(error)
except discord.Forbidden:
pass # /shrug
def get_music_state(self, guild_id):
return self.music_states.setdefault(guild_id, GuildMusicState(self.bot.loop))
Here's a basic example of one approach to this problem. We keep a global reference to some unique value every time the play command is received. The play coroutine will sleep after executing, and then disconnect only if the global value has not changed while it is sleeping.
from discord.ext import commands
bot = Bot('/')
last_play = None
#bot.command()
async def play(ctx):
global last_play
# Do the actual work
obj = object()
last_play = id(obj)
await asyncio.sleep(300)
if last_play == id(obj):
# disconnect logic
bot.run("token")

Categories

Resources