Zurück
Discort Bot by Bekim Jahmurataj
main.py
import datetime
import json
import discord
import pytz
from dateutil import parser
from discord.ext import commands, tasks, commands
from Zahnräder.Nachrichten import *
path = "/Zahnräder/Nachrichten"
#Klasse / variabel / Discort klasse
class MyDiscordBot(commands.Bot):
def __init__(self, intents):
super().__init__(command_prefix="$", intents=intents)
#Ban Woörter Liste
ban_words=["arsch" , "hund" , " "]
# Wenn der Bot startklar ist
async def on_ready(self):
print("Bot ist startklar!")
#json Dattei durchsuchen
with open('banned_members.json', 'r') as banned_member_file:
self.banned_members = json.load(banned_member_file)
self.checkBannedUsers.start()
#await self.add_cog(Nachrichten.Nachrichten(self))
#print(self.banned_members['name'])
await self.load_extension("Zahnräder.Nachrichten")
await self.checkMessages()
await self.tree.sync()
# Wenn eine nachricht geschrieben wird:
async def on_message(self, message):
if message.author == self.user:
return
await self.checkMessage(message)
print("Nachricht von" , message.author.name , "| Auf Server:" , message.guild , "| In Channel:" , message.channel ,"")
print(message.content)
#SPamt Personen zu
#await message.author.send("Hey das ist eine persönliche Nachricht", delete_after=3)
#!help Befehl
if message.content.startswith("!help"):
await message.channel.send('Hier die hilfe: / Befehle /help , /stats , /delete messages from username , /delete messages older Jahr Monat Tag Stunde Minute ,', file=discord.File("C:/Users/Bekim/Desktop/2.png"))
#!stats Befehl
if message.content.startswith("!stats"):
completeText = message.content.split(" ")[1:]
print(completeText)
completeName = ""
for namePart in completeText:
completeName += namePart
allMembers = message.guild.members
for member in allMembers:
if member.name.replace(" ", "") == completeName:
await message.channel.send("Hier die Stats von: " + member.name, delete_after=3)
return
await message.channel.send("User nicht gefunden", delete_after=3)
#!delete message from Befehl
if message.content.startswith("!delete messages from"):
completeText = message.content.split(" ")[3:]
# print(completeText)
completeName = ""
for namePart in completeText:
completeName = completeName + " " + namePart
# print(completeName.strip())
member = discord.utils.get(message.guild.members, name=completeName.strip())
allTextChannels = message.guild.text_channels
for channel in allTextChannels:
async for message in channel.history(limit=200):
if message.author == member:
await message.delete()
#!delete message older Befehl
if message.content.startswith("!delete messages older"):
timeString = message.content.split(" ")[3:]
# print (completeText)
completeDateString = ""
for date in timeString:
completeDateString = completeDateString + " " + date
print(completeDateString.strip())
inputDate = parser.parse(completeDateString.strip())
inputDate = pytz.utc.localize(inputDate)
allTextChannels = message.guild.text_channels
for channel in allTextChannels:
async for message in channel.history(before=inputDate):
if message.created_at < inputDate:
await message.delete()
if message.content.startswith("info"):
fullName = message.content.split(" ")[1:]
fullName = " ".join(fullName)
member = discord.utils.get(message.guild.members, name=fullName)
print(member)
memberInfoCard = discord.Embed(title=member.name)
memberInfoCard.color = discord.Color.gold()
memberInfoCard.set_thumbnail(url=member.display_avatar.url)
memberInfoCard.description = "Info über User"
memberInfoCard.set_author(name=message.author.name, url="https://www.google.de", icon_url=message.author.display_avatar.url)
memberInfoCard.add_field(
name="ID",
value=str(member.id),
inline=False
)
memberInfoCard.add_field(
name="Mitglied seit",
value=str(member.joined_at.strftime("%d %B %Y")),
inline=True
)
memberInfoCard.add_field(
name="Status",
value=member.desktop_status,
inline=True
)
memberInfoCard.add_field(
name="Rollen",
value=", ".join(role.name for role in member.roles if role.name != "@everyone"),
inline=False
)
memberInfoCard.set_footer(
text="This message was created by a Beks Bot"
)
file = discord.File("C://Users/Bekim/Desktop/2.png", filename="2.png")
memberInfoCard.set_image(url="attachment://2.png")
await message.channel.send(file=file, embed=memberInfoCard)
await self.process_commands(message)
#Ban Words Befehle vor dem Start
async def checkMessages(self):
server = self.get_guild(1060846642087084032)
allTextChannels = server.text_channels
for channel in allTextChannels:
async for message in channel.history():
if message.content in self.ban_words:
await message.delete()
#Ban Words nach dem Start
async def checkMessage(self, message):
if message.content in self.ban_words:
await message.delete()
self.banned_members[message.author.id] = str(datetime.datetime.now() + datetime.timedelta(seconds=10))
with open('banned_members.json', 'w') as banned_member_file:
json.dump(self.banned_members, banned_member_file)
await message.author.ban()
#Reaktions
# async def on_reaction_add(self, reaction, user):
# print(reaction)
# print(user)
async def on_raw_reaction_add(self, payload):
#print(payload)
channel = self.get_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
author = discord.utils.get(channel.guild.members, id=payload.user_id)
bull_role = discord.utils.get(channel.guild.roles, name='IT Security')
hack_role = discord.utils.get(channel.guild.roles, name='Hacker')
#print(channel)
#print(message.content)
if channel.name == "get_role" and message.content.startswith("Reagiere auf diese Nachricht, um eine Rolle zu bekommen."):
if payload.emoji.name == "🕵️♂️":
await payload.member.add_roles(hack_role)
await author.remove_roles(hack_role)
if payload.emoji.name == "👮":
await author.remove_roles(bull_role)
await payload.member.add_roles(bull_role)
#ARolle bei Server joinen
async def on_member_join(self, member):
role = discord.utils.get(member.guild.roles, name='join')
await member.add_roles(role)
#unBann Befehle
@tasks.loop(seconds=5)
async def checkBannedUsers(self):
for key, value in self.banned_members.items():
unban_time = parser.parse(value)
if unban_time < datetime.datetime.now():
server = self.get_guild(1060846642087084032)
user_to_unban = await self.fetch_user(int(key))
await server.unban(user_to_unban)
self.banned_members.pop(key)
with open("banned_members.json", 'w') as banned_members_file:
json.dump(self.banned_members, banned_members_file)
return
intents = discord.Intents.all()
discordBot = MyDiscordBot(intents=intents)
#DiscordBot Token Befehl
discordBot.run ("BOT TOKEN")
/Zahnräder/Nachrichten.py
from discord.ext import commands
import discord
from discord import app_commands
class MusicButton(discord.ui.Button):
def __init__(self, text, buttonStyle, mode, bot):
super().__init__(label=text, style=buttonStyle) #url="https://www.googl.de")
self.mode = mode
self.bot = bot
async def callback(self, interaction: discord.Interaction):
#await interaction.response.send_message("hallo")
await interaction.response.defer()
voice_channel = discord.utils.get(interaction.guild.voice_channels, name="Allgemein")
voice_client = discord.utils.get(self.bot.voice_clients, channel=voice_channel)
if voice_client == None:
voice_client = await voice_channel.connect()
if self.mode == 0:
voice_client.play(discord.FFmpegPCMAudio(source="./Musik/Russ_-_Seduce.mp3" , executable="ffmpeg.exe"))
elif self.mode == 1:
voice_client.pause()
elif self.mode == 2:
voice_client.resume()
elif self.mode == 4:
voice_client.play(discord.FFmpegPCMAudio(source="./Musik/Boris Brejcha.mp3" , executable="ffmpeg.exe"))
else:
voice_client.stop()
await voice_client.disconnect()
class MusicView(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.add_item(MusicButton("Play", discord.ButtonStyle.primary, 0, bot))
self.add_item(MusicButton("Pause", discord.ButtonStyle.secondary, 1, bot))
self.add_item(MusicButton("Resume", discord.ButtonStyle.green, 2, bot))
self.add_item(MusicButton("Stop", discord.ButtonStyle.red, 3, bot))
self.add_item(MusicButton("Next", discord.ButtonStyle.red, 4, bot))
self.bot=bot
class SelectMenu(discord.ui.Select):
def __init__(self):
super().__init__(placeholder="Wähle dein Auto", max_values=2, min_values=1)
self.add_option(label="Mazda RX8", description="Enthält einen Wankelmotor", emoji="🍆")
self.add_option(label="Mercedes CL500", description="Enthält einen Wankelmotor", emoji="😎")
self.add_option(label="Toyota Supra", description="Enthält einen Wankelmotor", emoji="👌")
self.add_option(label="Nissan GTR R34", description="Enthält einen Wankelmotor", emoji="😃")
self.add_option(label="Audi RS3", description="Enthält einen Wankelmotor", emoji="😋")
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Sie haben {self.values} ausgewählt")
class ChannelSelectMenu(discord.ui.ChannelSelect):
def __init__(self):
super().__init__(placeholder="Wähle einen Texthannel aus", channel_types=[discord.ChannelType.text], max_values=1)
async def callback(self, interaction: discord.Interaction):
await interaction.response.defer()
channel = await self.values[0]. fetch()
await channel.send("was geht")
class SelectionView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.add_item(SelectMenu())
self.add_item(ChannelSelectMenu())
class Nachrichten(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message_edit(self, before, after):
await before.channel.send(f"Before: {before.content}")
await before.channel.send(f"After: {after.content}")
@commands.command()
async def welcome(self, ctx):
await ctx.reply("arg")
@app_commands.command(name="delete_messages", description="Delete Messages")
#@app_commands.checks.has_role("Hacker")
async def deletemessages(self, interaction: discord.Interaction, number: int, member: discord.Member=None):
delete_counter = 0
await interaction.response.send_message("Wird Erledigt :")
async for message in interaction.channel.history():
if message.author == member or member == None:
await message.delete()
delete_counter += 1
if delete_counter == number:
break
@deletemessages.error
async def messages_error(self, interaction: discord.Integration, error: app_commands.AppCommandError):
if isinstance(error, app_commands.MissingRole):
await interaction.response.send_message(str(error), ephemeral=True)
@app_commands.command(name="music")
async def music(self, interaction: discord.Interaction):
await interaction.response.send_message(view=MusicView(self.bot))
@app_commands.command(name="selection")
async def selection(self, interaction: discord.Interaction):
await interaction.response.send_message(view=SelectionView())
async def setup(bot):
await bot.add_cog(Nachrichten(bot))