Skip to content

Discord bot #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
PAYZE_API_KEY="{Key:Secret}"
PAYZE_API_KEY="{Key:Secret}"
DISCORD_BOT_TOKEN=<Discord Bot Token>
1 change: 1 addition & 0 deletions bitcamp/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

"accounts",
"content",
"bitcamper",

"django.contrib.admin",
"django.contrib.auth",
Expand Down
Empty file added bitcamper/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions bitcamper/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
33 changes: 33 additions & 0 deletions bitcamper/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from django.apps import AppConfig
import os, sys, threading, asyncio
import logging

logger = logging.getLogger(__name__)

class BitCamperConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "bitcamper"

def ready(self):
if bool(int(os.environ.get("DISCORD_BOT_STARTED", "0"))):
logger.info("[BitCamper] Discord bot is already running")
elif "runserver" in sys.argv:
self.start_bot()

def start_bot(self):
logger.info("[BitCamper] Starting the Discord bot")
from . import bot

threading.Thread(
target=bot.start
).start()

os.environ["DISCORD_BOT_STARTED"] = "1"

def stop_bot(self, client):
logger.info("[BitCamper] Stopping the Discord bot")

loop = asyncio.get_event_loop()
loop.create_task(client.close())

os.environ["DISCORD_BOT_STARTED"] = "0"
85 changes: 85 additions & 0 deletions bitcamper/bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import discord, os, re

intents = discord.Intents.default()
intents.message_content = True
intents.members = True

client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)

@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=1153858189884915752))
print(f"[bitcamper] logged in as {client.user.name}")

@tree.command(name="ping", description="Ping", guild=discord.Object(id=1153858189884915752))
async def ping_command(interaction):
await interaction.response.send_message(
f"**{int(client.latency*1000)}**ms"
)

@tree.command(name="mkchannels", description="Create private channels for members with a specified role.", guild=discord.Object(id=1153858189884915752))
async def create_channels(interaction, role: discord.Role = None):
if not interaction.user.guild_permissions.administrator:
await interaction.response.send_message(
f"Only administrators can use this command.", ephemeral=True
)
return

guild = interaction.guild

if role:
members_to_process = [member for member in guild.members if role in member.roles]
else:
members_to_process = [member for member in guild.members if len(member.roles) == 1 and guild.default_role in member.roles]

creating, skipping = [], []
for member in members_to_process:
if re.sub(r"[^\w]", "", member.name.lower()) in [channel.name for channel in member.guild.channels]:
skipping.append(member.name)
else:
creating.append(member.name)

message = f"Creating channels for {', '.join(creating)}."

if len(creating) <= 0:
message = "Creating channels for nobody."
if len(skipping) > 0:
message += f" Skipping creating channels for {', '.join(skipping)}. (Channels already exist)"

await interaction.response.send_message(
message, ephemeral=True
)

for member in members_to_process:
channel_name = re.sub(r"[^\w]", "", member.name.lower())

if channel_name in [channel.name for channel in member.guild.channels]:
continue

await on_member_join(member)

@client.event
async def on_member_join(member):
channel_name = f"{member.name}"
guild = member.guild
overwrites = {
guild.default_role: discord.PermissionOverwrite(read_messages=False),
member: discord.PermissionOverwrite(read_messages=True),
client.user: discord.PermissionOverwrite(read_messages=True)
}

if "ახალი მოსწავლე" in [category.name for category in guild.categories]:
category = [category for category in guild.categories if category.name == "ახალი მოსწავლე"][0]
else:
category = await guild.create_category("ახალი მოსწავლე")

new_channel = await guild.create_text_channel(channel_name, overwrites=overwrites, category=category)

await new_channel.send(f"გამარჯობა, {member.mention}! იმისათვის რომ მოგენიჭოთ მოსწავლის როლი და გამოგიჩნდეთ სასწავლო არხები, გთხოვთ მოგვწეროთ საიტზე რეგისტრაციისას გამოყენებული email და მოსწავლის ასაკი.")

def start():
client.run(os.environ["DISCORD_BOT_TOKEN"])

if __name__ == "__main__":
client.run(os.environ["DISCORD_BOT_TOKEN"])
Empty file.
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ django
djangorestframework
django-cors-headers
drf-spectacular
psycopg2
psycopg2-binary
discord.py
gunicorn
requests
Expand Down