Skip to content

Commit 34e3e2b

Browse files
committed
Migrating to discord.py 2
1 parent ba17552 commit 34e3e2b

File tree

13 files changed

+126
-107
lines changed

13 files changed

+126
-107
lines changed

Procfile

Lines changed: 0 additions & 1 deletion
This file was deleted.

cogs/converters.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,5 +41,5 @@ async def decode_binary(self, ctx, *, arg):
4141
embed = discord.Embed(color = 0xff8080, title = 'Binary Decoder', description = json_data['text'])
4242
await ctx.send(embed = embed)
4343

44-
def setup(bot):
45-
bot.add_cog(Convert(bot))
44+
async def setup(bot):
45+
await bot.add_cog(Convert(bot))

cogs/games.py

Lines changed: 22 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,37 @@
11
import random
22
import discord
33
from discord.ext import commands
4-
from discord_components import DiscordComponents, Button, ButtonStyle
54

65
class Games(commands.Cog):
76
def __init__(self, bot):
87
self.bot = bot
9-
8+
9+
# noinspection PyUnresolvedReferences
10+
class JankenButtons(discord.ui.View):
11+
def __init__(self):
12+
super().__init__()
13+
14+
@discord.ui.button(label="Камень", emoji="🗿", style=discord.ButtonStyle.blurple)
15+
async def rock_button(self, interaction: discord.Interaction, button: discord.ui.Button):
16+
await interaction.response.send_message("Камень")
17+
18+
@discord.ui.button(label="Ножницы", emoji="✂️", style=discord.ButtonStyle.red)
19+
async def scissors_button(self, interaction: discord.Interaction, button: discord.ui.Button):
20+
await interaction.response.send_message("Ножницы")
21+
22+
@discord.ui.button(label="Бумага", emoji="📄", style=discord.ButtonStyle.gray)
23+
async def paper_button(self, interaction: discord.Interaction, button: discord.ui.Button):
24+
await interaction.response.send_message("Бумага")
25+
1026
@commands.command(aliases=['rps', 'rockpaperscissors'])
1127
async def janken(self, ctx):
1228
description = 'Сыграй со мной в камень ножницы бумагу! выбери один из вариантов ниже:'
1329
embed = discord.Embed(color = 0xffcd4c, title = f'{ctx.message.author}: Камень Ножницы Бумага', description = description)
14-
gamebar = await ctx.send(
15-
embed = embed,
16-
components = [
17-
[
18-
Button(style = ButtonStyle.blue, label = 'Камень', emoji = '🗿'),
19-
Button(style = ButtonStyle.red, label = 'Ножницы', emoji = '✂️'),
20-
Button(style = ButtonStyle.gray, label = 'Бумага', emoji = '📄'),
21-
]
22-
])
30+
await ctx.send(embed = embed)
2331
answers = ['Камень', 'Ножницы', 'Бумага']
2432
choice = random.choice(answers)
2533

26-
responce = await self.bot.wait_for('button_click', check = lambda message: message.author == ctx.author)
27-
28-
async def victory():
29-
await gamebar.edit(embed=discord.Embed(color = embed.color, title = embed.title, description = f'{embed.description} \n Ты выбрал `{responce.component.label}`, а я выбрал `{choice}` \n Победа!!!'), components=[])
30-
31-
if responce.component.label == choice:
32-
await gamebar.edit(embed=discord.Embed(color = embed.color, title = embed.title, description = f'{embed.description} \n Ты выбрал `{responce.component.label}`, а я выбрал `{choice}` \n Ничья!'), components=[])
33-
34-
elif responce.component.label == 'Камень' and choice == 'Ножницы':
35-
await victory()
36-
37-
elif responce.component.label == 'Ножницы' and choice == 'Бумага':
38-
await victory()
39-
40-
elif responce.component.label == 'Бумага' and choice == 'Камень':
41-
await victory()
42-
43-
else:
44-
await gamebar.edit(embed=discord.Embed(color = embed.color, title = embed.title, description = f'{embed.description} \n Ты выбрал `{responce.component.label}`, а я выбрал `{choice}` \n Проигрыш :('), components=[])
34+
#await gamebar.edit(embed=discord.Embed(color = embed.color, title = embed.title, description = f'{embed.description} \n Ты выбрал `{responce.component.label}`, а я выбрал `{choice}` \n Проигрыш :('), components=[])
4535

4636

4737
@commands.command()
@@ -77,5 +67,5 @@ async def slots(self, ctx):
7767
embed.set_footer(text = footer, icon_url = "https://i.imgur.com/uZIlRnK.png")
7868
await ctx.send(embed = embed)
7969

80-
def setup(bot):
81-
bot.add_cog(Games(bot))
70+
async def setup(bot):
71+
await bot.add_cog(Games(bot))

cogs/help.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import discord
22
from discord.ext import commands
3-
from discord_components import DiscordComponents, Button, ButtonStyle
43
from config import settings
54

65
class Help(commands.Cog):
@@ -139,18 +138,20 @@ async def server_info(self, ctx):
139138
embed = discord.Embed(color = 0xffcd4c , title = 'server_info', description = help_text)
140139
await ctx.send(embed = embed)
141140

141+
class ISOCodes(discord.ui.View):
142+
def __init__(self):
143+
super().__init__()
144+
self.__url = "https://snipp.ru/handbk/iso-639-1"
145+
self.add_item(discord.ui.Button(label='Коды ISO 639-1', url=self.__url))
146+
142147
@help.command()
143148
async def translate(self, ctx):
144-
help_text = (f'```{settings.get("prefix")}translate <язык> <текст>```\n'
145-
'Переводит ваш текст, язык указывается по стандарту ISO 639-1\n'
146-
'Полный список наименований будет доступен после нажатия на кнопку ниже')
149+
help_text = (f"```{settings.get('prefix')}translate <язык> <текст>```\n"
150+
"Переводит ваш текст, язык указывается по стандарту ISO 639-1\n"
151+
"Полный список наименований будет доступен после нажатия на кнопку ниже")
147152
embed = discord.Embed(color = 0xffcd4c , title = 'translate', description = help_text)
148-
await ctx.send(
149-
embed = embed,
150-
components = [
151-
Button(style = ButtonStyle.URL, url = 'https://snipp.ru/handbk/iso-639-1', label='Коды ISO 639-1')
152-
])
153-
153+
await ctx.send(embed=embed, view=self.ISOCodes())
154+
154155
@help.command()
155156
async def poll(self, ctx):
156157
help_text = (f'```{settings.get("prefix")}poll "вопрос" "вариант 1" "вариант 2"```\n'
@@ -160,10 +161,9 @@ async def poll(self, ctx):
160161
'```{settings.get("prefix")}poll "Какие чипсы вы предпочитаете" "Lais" "Prongls" "2 корочки"```\n'
161162
'Плохой пример:\n'
162163
'```{settings.get("prefix")}poll Какие чипсы вы предпочитаете Lais Prongls 2 корочки```\n'
163-
'В плохом примере нету кавычек, соответственно, за вопрос будет считыватся только `Какие`, остальное будет вариантами ответа\n'
164-
'**Для вывода результата плохого примера, нажмите на кнопку ниже**')
164+
'В плохом примере нету кавычек, соответственно, за вопрос будет считыватся только `Какие`, остальное будет вариантами ответа\n')
165165
embed = discord.Embed(color = 0xffcd4c , title = 'poll', description = help_text)
166-
await ctx.send(embed = embed, components = [[Button(style = ButtonStyle.blue, label = 'Результат Плохого Примера')]])
166+
await ctx.send(embed=embed)
167167

168168
@help.command()
169169
async def echo(self, ctx):
@@ -217,5 +217,5 @@ async def janken(self, ctx):
217217
embed = discord.Embed(color = 0xffcd4c , title = 'Камень-Ножницы-Бумага', description = help_text)
218218
await ctx.send(embed = embed)
219219

220-
def setup(bot):
221-
bot.add_cog(Help(bot))
220+
async def setup(bot):
221+
await bot.add_cog(Help(bot))

cogs/information.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,5 +42,5 @@ async def server_info(self, ctx):
4242
embed.set_footer(text = f"Запросил {ctx.author}", icon_url = ctx.author.avatar_url)
4343
await ctx.send(embed = embed)
4444

45-
def setup(bot):
46-
bot.add_cog(Information(bot))
45+
async def setup(bot):
46+
await bot.add_cog(Information(bot))

cogs/listeners.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,6 @@ async def on_ready(self):
3737
await self.bot.change_presence(status=discord.Status.online, activity=discord.Game(f"{settings.get('prefix')}help"))
3838
await asyncio.sleep(5)
3939

40-
def setup(bot):
41-
bot.add_cog(ErrorListener(bot))
42-
bot.add_cog(OnReady(bot))
40+
async def setup(bot):
41+
await bot.add_cog(ErrorListener(bot))
42+
await bot.add_cog(OnReady(bot))

cogs/moderation.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ async def clear(self, ctx, arg1):
1414
amount = int(arg1)
1515
await ctx.message.delete()
1616
await ctx.channel.purge(limit = amount)
17-
await ctx.send(f'{self.bot.get_emoji(settings["emojis"]["squid_cleaning"])} Очищено {amount} сообщений! Запрос на очистку от {ctx.author.mention}')
17+
await ctx.send(f'{self.bot.get_emoji(settings["emojis"]["squid_cleaning"])} {ctx.author.mention}: Очищено {amount} сообщений!')
1818

1919
@has_permissions(kick_members = True)
2020
@commands.command()
@@ -57,5 +57,5 @@ async def idclear_error(self, ctx, error):
5757
elif isinstance(error, CommandInvokeError):
5858
await ctx.send('❌ У бота нету привилегий управления сообщениями! Пожалуйста, удалите бота из сервера, и добавьте его снова по следующей ссылке: https://discord.com/api/oauth2/authorize?client_id=699912361481470032&permissions=8&scope=bot')
5959

60-
def setup(bot):
61-
bot.add_cog(Moderation(bot))
60+
async def setup(bot):
61+
await bot.add_cog(Moderation(bot))

cogs/music.py

Lines changed: 49 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import datetime
33
import discord
44
from discord.ext import commands
5-
from discord_components import DiscordComponents, Button, ButtonStyle
65
from youtube_dl import YoutubeDL
76
from config import settings
87

@@ -55,9 +54,9 @@ def get_by_id(self, id):
5554

5655

5756
class Music(commands.Cog):
58-
def __init__(self, bot):
57+
def __init__(self, bot, intents):
5958
self.bot = bot
60-
self.__client = discord.Client()
59+
self.__client = discord.Client(intents=intents)
6160
self.__queue = Queue()
6261

6362
async def __connect(self, ctx):
@@ -87,6 +86,41 @@ def __get_url(self, extracted):
8786
url = extracted['formats'][0]['url']
8887
return url
8988

89+
# noinspection PyUnresolvedReferences
90+
class PlayerButtons(discord.ui.View):
91+
def __init__(self, voice_chat, context, leave, stop, pause, resume, skip):
92+
super().__init__()
93+
self.__vc = voice_chat
94+
self.__ctx = context
95+
self.__leave = leave
96+
self.__stop = stop
97+
self.__pause = pause
98+
self.__resume = resume
99+
self.__skip = skip
100+
101+
@discord.ui.button(style=discord.ButtonStyle.red, label='Выход', emoji='🚪')
102+
async def button_leave(self, interaction: discord.Interaction, button: discord.ui.Button):
103+
await interaction.response.send_message("Хорошо блин, ухожу, тупой ты дебил", tts=True, delete_after=8)
104+
self.__leave(self.__ctx)
105+
106+
@discord.ui.button(style=discord.ButtonStyle.red, label='Стоп', emoji='🛑')
107+
async def button_stop(self, interaction: discord.Interaction, button: discord.ui.Button):
108+
await interaction.response.send_message("Хорошо, тормознул", tts=True, delete_after=8)
109+
self.__stop(self.__ctx)
110+
111+
@discord.ui.button(style=discord.ButtonStyle.blurple, label='Пауза / Продолжить', emoji='⏯️')
112+
async def button_pause_resume(self, interaction: discord.Interaction, button: discord.ui.Button):
113+
if self.__vc.is_playing():
114+
await interaction.response.send_message("Усё, усё, пауза", tts=True, delete_after=8)
115+
self.__vc.pause()
116+
elif self.__vc.is_paused():
117+
await interaction.response.send_message("Играем дальше, значит. Ты задолбал", tts=True, delete_after=8)
118+
self.__vc.resume()
119+
120+
@discord.ui.button(style=discord.ButtonStyle.blurple, label='Пропустить', emoji='⏭️')
121+
async def button_skip(self, interaction: discord.Interaction, button: discord.ui.Button):
122+
await interaction.response.send_message("Эту песню мы попускаем, потому что гивно", tts=True, delete_after=8)
123+
self.__skip(self.__ctx)
90124

91125
async def __play(self, context, url, video):
92126
self.__vc.play(discord.FFmpegPCMAudio(executable=settings['path_to_ffmpeg'], source = url, **FFMPEG_OPTIONS), after = lambda e: self.__skip(context = context))
@@ -97,18 +131,14 @@ async def __play(self, context, url, video):
97131
.add_field(name = '⌛ Продолжительность', value = datetime.timedelta(seconds=duration))
98132
.add_field(name = '🙃 Запросил', value = context.author.mention)
99133
.set_thumbnail(url = video.get('thumbnail')) )
100-
firstmessage = await context.send(
101-
embed = embed,
102-
components = [
103-
[
104-
Button(style = ButtonStyle.red, label = 'Выход', emoji = '🚪'),
105-
Button(style = ButtonStyle.red, label = 'Стоп', emoji = '🛑'),
106-
Button(style = ButtonStyle.blue, label = 'Пауза / Продолжить', emoji = '⏯️'),
107-
Button(style = ButtonStyle.blue, label = 'Пропустить', emoji = '⏭️'),
108-
]
109-
])
110-
111-
self.__playing_now_embed = firstmessage
134+
await context.send(embed = embed, view=self.PlayerButtons(self.__vc,
135+
context,
136+
self.__leave,
137+
self.__stop,
138+
self.__pause,
139+
self.__resume,
140+
self.__skip))
141+
112142
title = video.get('title')
113143
self.__queue.set_playing_now(title)
114144
while self.__vc.is_playing:
@@ -121,7 +151,6 @@ async def __play(self, context, url, video):
121151
await responce.respond(content = '🚪 Бот вышел из голосового чата')
122152
return
123153
case 'Стоп':
124-
await self.__playing_now_embed.edit(embed=embed, components=[Button(style = ButtonStyle.red, label = 'Выход', emoji = '🚪')])
125154
self.__stop(context)
126155
await responce.respond(content = '🛑 Остановлено!')
127156
return
@@ -138,7 +167,6 @@ async def __play(self, context, url, video):
138167
await responce.respond(content = '⏭️ Скипаю...')
139168
self.__skip(context)
140169

141-
142170
def __skip(self, context):
143171
asyncio.run_coroutine_threadsafe(self.__playing_now_embed.edit(components=[]), self.bot.loop)
144172
if self.__vc.is_playing():
@@ -171,7 +199,8 @@ def __pause(self, context):
171199
def __resume(self, context):
172200
if not self.__vc.is_playing():
173201
self.__vc.resume()
174-
elif self.__vc.is_playing():asyncio.run_coroutine_threadsafe(context.send('🤪 Лол, я не на паузе, зачем ты ввёл эту команду?!'), self.bot.loop)
202+
elif self.__vc.is_playing():
203+
asyncio.run_coroutine_threadsafe(context.send('🤪 Лол, я не на паузе, зачем ты ввёл эту команду?!'), self.bot.loop)
175204

176205
@commands.command()
177206
async def play(self, ctx, *, arg):
@@ -259,5 +288,5 @@ async def resume(self, ctx):
259288
await ctx.message.add_reaction("🤡")
260289
await ctx.send(f"{self.bot.get_emoji(settings['emojis']['wuuut'])} Для начала введи хотя бы `{settings.get('prefix')}play [название_песни]`")
261290

262-
def setup(bot):
263-
bot.add_cog(Music(bot))
291+
async def setup(bot, intents):
292+
await bot.add_cog(Music(bot, intents))

cogs/text.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,5 +63,5 @@ async def poll(self, ctx, question, *options: str):
6363
embed.set_footer(text= f'Poll ID: {react_message.id} \nКстати! Вопрос нужно указывать в кавычках!' )
6464
await react_message.edit(embed=embed)
6565

66-
def setup(bot):
67-
bot.add_cog(Text(bot))
66+
async def setup(bot):
67+
await bot.add_cog(Text(bot))

config.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,4 @@
2828
discord.Activity(type=discord.ActivityType.watching, name="поруху с собакой"),
2929
discord.Game(name="игру"),
3030
discord.Game(name="ебанину нахуй")]
31-
}
31+
}

0 commit comments

Comments
 (0)