from vk_api.audio import VkAudio
import requests
from bs4 import BeautifulSoup
import discord
from discord.ext import commands
from discord import Status
import random
import asyncio
from discord.utils import get
from yt_dlp import YoutubeDL
vk_session = VkApi(token='мой токен вк')
vk = vk_session.get_api()
config = {
'token': 'токен бота дс',
'prefix': '$',
}
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=config['prefix'], intents=intents)
bot.remove_command('help')
@bot.event
async def on_ready():
statuses = ['Ну а что поделать?', 'Да да я...', '/help', 'Че смотришь?']
while True:
await bot.change_presence(status=discord.Status.dnd)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=random.choice(statuses)))
await asyncio.sleep(10)
# @bot.command()
# async def play(ctx, url, description='Заказ музыки / Временно не работает'):
# """
# Проигрывает музыку с YouTube в голосовом канале автора команды.
# Использование: /play [URL YouTube видео]
# """
# if ctx.author.voice:
# voice_channel = ctx.author.voice.channel
# voice_client = get(bot.voice_clients, guild=ctx.guild)
# if voice_client and voice_client.is_connected():
# await voice_client.move_to(voice_channel)
# else:
# voice_client = await voice_channel.connect()
# ydl_opts = {'format': 'bestaudio'}
# with YoutubeDL(ydl_opts) as ydl:
# info = ydl.extract_info(url, download=False)
# url2 = info['formats'][0]['url']
# voice_client.play(discord.FFmpegPCMAudio(url2, before_options='-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5'))
# await ctx.send(f'Воспроизвожу музыку: {info["title"]}')
# else:
# await ctx.send('Вы должны быть в голосовом канале, чтобы использовать эту команду.')
# @bot.command()
# async def stop(ctx):
# voice_client = ctx.voice_client
# if voice_client:
# await voice_client.disconnect()
# await ctx.send('Бот покинул голосовой канал.')
# else:
# await ctx.send('Бот не находится в голосовом канале.')
@bot.command(description='Тестовая команда')
async def command(ctx):
"""
Тестовая команда
"""
await ctx.message.delete()
await ctx.send('Я робот')
blocked_words = ['пидор', 'пидорасина', 'негр', 'негритосик', 'хохол', 'русня'] # Список запрещенных слов
@bot.event
async def on_message(message):
for word in blocked_words:
if word in message.content.lower():
await message.delete() # Удаление сообщения-нарушителя
await message.channel.send(f'{message.author.mention}, не пиши такие плохие слова. :smiling_face_with_tear:') # Отправка сообщения с упоминанием нарушителя
break
await bot.process_commands(message) # Обработка других команд
@bot.command()
async def furry(ctx,description='Узнай насколько ты фурри'):
"""
Показывает на сколько ты фурри.
Использование: /furry
"""
percentage = random.randint(0, 100) # Генерация случайного числа от 0 до 100
if percentage < 20:
await ctx.send(f"Ты фурри на {percentage}%, так держать!")
else:
await ctx.send(f"Ты фурри на {percentage}%, фу мерзость!")
@bot.command()
async def help(ctx, description='Список всех комманд'):
"""Все команды бота.
Использование: /help
"""
embed = discord.Embed(title="Всевозможные команды", description="Список доступных команд бота:", color=discord.Color.blue())
for command in bot.commands:
embed.add_field(name=command.name, value=command.help, inline=False)
await ctx.send(embed=embed)
@bot.command()
@commands.has_any_role('Амикус', 'Пуфыстый модератор') # проверка на наличие ролей администратора или модератора
async def clear(ctx, amount: int, description='Удаление сообщений'):
"""
Удаляет указанное количество сообщений из текущего канала чата.
Использование: /clear [количество]
"""
await ctx.channel.purge(limit=amount+1)
await ctx.send(f'Удалено {amount} сообщений.')
@bot.command()
async def users(ctx, description='Кол-во участников сервера'):
"""
Показывает кол-во людей и ботов на этом дискорд сервере.
Использование: /users
"""
member_count = len(ctx.guild.members)
await ctx.send(f"На этом сервере сейчас {member_count} участника(ов).")
# @bot.command() #рандомные реакции
# async def random_reactions(ctx):
# messages = await ctx.channel.history(limit=None).flatten() # получение всех сообщений в текущем канале
# random_messages = random.choices(messages, k=int(len(messages) * 0.9))
# for message in random_messages:
# reactions = [':white_check_mark:', ':rainbow:', ':heart:', ':saluting_face:', ':skull_crossbones:'] # список рандомных реакций
# reaction = random.choice(reactions) # выбор рандомной реакции
# await message.add_reaction(reaction) # добавление реакции к сообщению
@bot.event #рандомные реакции
async def on_message(message):
if random.random() < 0.2:
emoji = random.choice(bot.emojis)
try:
await message.add_reaction(emoji)
except discord.errors.HTTPException:
pass
await bot.process_commands(message)
@bot.command()
async def play(ctx, query):
"""
Проигрывает музыку с Вконтакте в голосовом канале автора команды.
Использование: /play [название трека или исполнителя]
"""
if ctx.author.voice:
voice_channel = ctx.author.voice.channel
voice_client = get(bot.voice_clients, guild=ctx.guild)
if voice_client and voice_client.is_connected():
await voice_client.move_to(voice_channel)
else:
voice_client = await voice_channel.connect()
vkaudio = VkAudio(vk)
try:
tracks = vkaudio.search(query)
if tracks:
track = tracks[0] # Получение первого трека из результатов поиска
url = track['url'] # Получение URL трека
response = requests.get(url, stream=True)
if response.status_code == 200:
filename = f'{track["artist"]} - {track["title"]}.mp3' # Формирование имени файла из исполнителя и названия трека
with open(filename, 'wb') as f:
f.write(response.content)
voice_client.play(discord.FFmpegPCMAudio(filename))
await ctx.send(f'Воспроизвожу музыку: {track["artist"]} - {track["title"]}')
else:
await ctx.send('Не удалось получить трек.')
else:
await ctx.send('Трек не найден.')
except KeyError:
await ctx.send('Произошла ошибка при поиске трека.')
else:
await ctx.send('Вы должны быть в голосовом канале, чтобы использовать эту команду.')
bot.run(config['token'])```
**Ошибки**
Traceback (most recent call last):
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\comp\Desktop\bot discrod\bot.py", line 167, in play
vkaudio = VkAudio(vk)
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\vk_api\audio.py", line 81, in __init__
self.user_id = vk.method('users.get')[0]['id']
TypeError: VkApiMethod.__call__() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: VkApiMethod.__call__() takes 1 positional argument but 2 were givenTraceback (most recent call last):
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\comp\Desktop\bot discrod\bot.py", line 167, in play
vkaudio = VkAudio(vk)
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\vk_api\audio.py", line 81, in __init__
self.user_id = vk.method('users.get')[0]['id']
TypeError: VkApiMethod.__call__() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\comp\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: VkApiMethod.__call__() takes 1 positional argument but 2 were given