onboard via embed in #welcome
This commit is contained in:
parent
60fd7c320d
commit
ea95c92fb9
138
main.py
138
main.py
|
@ -1,111 +1,87 @@
|
|||
import discord
|
||||
from discord.ext import commands
|
||||
import sqlite3
|
||||
from dotenv import load_dotenv
|
||||
import os
|
||||
from dotenv import load_dotenv
|
||||
import sqlite3
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Set up logging handler. Passed in at the end in bot.run
|
||||
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
|
||||
|
||||
# Load ENV file
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
# Gather variables from .env file
|
||||
BOT_TOKEN = os.getenv('BOT_TOKEN')
|
||||
CHANNEL_ID = int(os.getenv('BOT_CHANNEL_ID'))
|
||||
botCommandsEnable = True
|
||||
|
||||
if BOT_TOKEN is None:
|
||||
print("BOT TOKEN NOT FOUND IN ENV")
|
||||
exit()
|
||||
if CHANNEL_ID is None:
|
||||
print("NO CHANNEL SELECTED, DISABLING BOT COMMANDS")
|
||||
botCommandsEnable = False
|
||||
else:
|
||||
print(f'Channel ID selected: {CHANNEL_ID}')
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(filename='discord.log', level=logging.INFO)
|
||||
|
||||
# Define intents
|
||||
intents = discord.Intents.all()
|
||||
intents.members = True # Enable the member update intent
|
||||
intents.message_content = True # Enable the Privileged Content intent
|
||||
|
||||
# Set discord end bot commands to / prefix
|
||||
bot = commands.Bot(command_prefix='/', intents=intents)
|
||||
|
||||
# Connect to SQLite
|
||||
# Connect to SQLite database
|
||||
conn = sqlite3.connect('member_data.db')
|
||||
cursor = conn.cursor()
|
||||
c = conn.cursor()
|
||||
|
||||
# Create table if not exists
|
||||
c.execute('''CREATE TABLE IF NOT EXISTS members
|
||||
(user_id INTEGER PRIMARY KEY, username TEXT, nickname TEXT, join_datetime TEXT, onboarding_status INTEGER, last_change_datetime TEXT)''')
|
||||
|
||||
# Create Dataset if it doesn't exist already
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS members (
|
||||
user_id INTEGER PRIMARY KEY,
|
||||
username TEXT,
|
||||
nickname TEXT,
|
||||
join_date TEXT
|
||||
)
|
||||
''')
|
||||
conn.commit()
|
||||
|
||||
# Initialize bot
|
||||
bot = commands.Bot(command_prefix='/', intents=intents)
|
||||
|
||||
@bot.event
|
||||
async def on_ready():
|
||||
# When API connects and logs in.
|
||||
print(f'Bot logged in as {bot.user.name}')
|
||||
print(f'Logged in as {bot.user}')
|
||||
|
||||
# Send help command to bot-commands channel
|
||||
# channel = bot.get_channel(int(CHANNEL_ID))
|
||||
# await channel.send(f'Use /help to view available commands')
|
||||
# Find the #welcome channel
|
||||
welcome_channel_id = int(os.getenv('WELCOME_CHANNEL_ID'))
|
||||
welcome_channel = discord.utils.get(bot.get_all_channels(), id=welcome_channel_id)
|
||||
|
||||
# Check if welcome message has already been sent in the channel
|
||||
async for message in welcome_channel.history(limit=100):
|
||||
if message.author == bot.user and message.embeds:
|
||||
return # If the welcome message is found, exit the function
|
||||
|
||||
# Send welcome message in the #welcome channel
|
||||
view = discord.ui.View()
|
||||
button = discord.ui.Button(label="Complete Onboarding")
|
||||
view.add_item(button)
|
||||
embed = discord.Embed(title="Welcome to the Server!", description="Here's how to get started:")
|
||||
embed.add_field(name="Step 1:", value="Read the server rules in #rules channel.")
|
||||
embed.add_field(name="Step 2:", value="Check out people's projects.")
|
||||
embed.add_field(name="Step 3:", value="Complete Onboarding procedure to unlock the rest of the server.")
|
||||
embed.set_footer(text="Enjoy your stay!")
|
||||
await welcome_channel.send(embed=embed, view=view)
|
||||
|
||||
|
||||
@bot.event
|
||||
async def on_member_join(member):
|
||||
# Print user's name and ID in the console on new join
|
||||
print(f'New member joined: {member.name} (ID: {member.id}), joined at {member.joined_at}')
|
||||
print(member)
|
||||
# Check if member already exists in the database
|
||||
c.execute("SELECT * FROM members WHERE user_id = ?", (member.id,))
|
||||
existing_member = c.fetchone()
|
||||
|
||||
# Store member data in the database
|
||||
cursor.execute('INSERT INTO members (user_id, username, join_date) VALUES (?, ?, ?)',
|
||||
(member.id, member.name, datetime.now().strftime('%Y-%m-%d %H:%M:%S')))
|
||||
if not existing_member: # If it's the member's first time joining
|
||||
# Add new member to the database
|
||||
c.execute(
|
||||
"INSERT OR REPLACE INTO members (user_id, username, join_datetime, onboarding_status, last_change_datetime) VALUES (?, ?, ?, ?, ?)",
|
||||
(member.id, member.name, member.joined_at.isoformat(), 0, datetime.now(timezone.utc).isoformat()))
|
||||
conn.commit()
|
||||
|
||||
# Update member nickname
|
||||
await member.edit(nick=c.execute("SELECT nickname FROM members WHERE user_id = ?", (member.id,)).fetchone()[0])
|
||||
|
||||
@bot.command()
|
||||
async def commands(ctx):
|
||||
avail_commands = open("availcommands.txt", "r")
|
||||
await ctx.send(avail_commands.read())
|
||||
avail_commands.close()
|
||||
# Log member join
|
||||
logging.info(f'Member {member.name} joined the server.')
|
||||
|
||||
|
||||
@bot.command()
|
||||
async def setnick(ctx, new_nickname: str):
|
||||
|
||||
# Update user's nickname in the database
|
||||
cursor.execute('UPDATE members SET nickname = ? WHERE user_id = ?', (new_nickname, ctx.author.id))
|
||||
conn.commit()
|
||||
|
||||
# Retrieve the updated nickname from the database
|
||||
cursor.execute('SELECT nickname FROM members WHERE user_id = ?', (ctx.author.id,))
|
||||
updated_nickname = cursor.fetchone()[0]
|
||||
|
||||
# Print the updated nickname to the console
|
||||
print(f'Nickname updated for {ctx.author.name} (ID: {ctx.author.id}): {updated_nickname}')
|
||||
|
||||
member = ctx.guild.get_member(ctx.author.id)
|
||||
if member:
|
||||
try:
|
||||
await member.edit(nick=updated_nickname)
|
||||
print(f'Nickname updated on the server for {ctx.author.name}')
|
||||
except discord.Forbidden:
|
||||
print(f'Failed to update nickname on the server for {ctx.author.name}: Missing permissions')
|
||||
except discord.HTTPException as e:
|
||||
print(f'Failed to update nickname on the server for {ctx.author.name}: {e}')
|
||||
|
||||
# Close the database connection when the bot is stopped
|
||||
@bot.event
|
||||
async def on_disconnect():
|
||||
conn.close()
|
||||
async def on_member_remove(member):
|
||||
# Log member leave
|
||||
logging.info(f'Member {member.name} left the server.')
|
||||
|
||||
bot.run(BOT_TOKEN, log_handler=handler, log_level=logging.DEBUG)
|
||||
|
||||
# Load bot token and welcome channel id from .env file
|
||||
TOKEN = os.getenv('BOT_TOKEN')
|
||||
WELCOME_CHANNEL_ID = os.getenv('WELCOME_CHANNEL_ID')
|
||||
|
||||
# Start bot
|
||||
bot.run(TOKEN)
|
||||
|
|
Loading…
Reference in New Issue
Block a user