-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py.txt
206 lines (179 loc) · 8.25 KB
/
main.py.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import discord
from discord.ext import commands
import os
import aiohttp
import json
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Load environment variables
TOKEN = os.getenv('DISCORD_BOT_TOKEN')
GUILD_ID = int(os.getenv('DISCORD_GUILD_ID'))
GITHUB_REPO_OWNER = 'ChrisTitusTech'
GITHUB_REPO_NAME = 'WinUtil'
CONTRIBUTOR_ROLE_ID = int(os.getenv('CONTRIBUTOR_ROLE_ID'))
ADMIN_ROLE_ID = int(os.getenv('ADMIN_ROLE_ID'))
WEB_SERVER_URL = os.getenv('WEB_SERVER_URL')
FILE_PATH = 'user_records.json'
BRANCH_NAME = 'main'
AUTHORIZATION_URL = 'https://discord.com/oauth2/authorize?client_id=1264587568117448811&response_type=code&redirect_uri=http%3A%2F%2Fbotworks.callums.live%2Fapi%2Foauth2%2Fcallback&scope=identify+connections'
# Initialize bot with all intents enabled
intents = discord.Intents().all()
bot = commands.Bot(command_prefix='!', intents=intents)
async def fetch_user_records():
async with aiohttp.ClientSession() as session:
async with session.get(f"{WEB_SERVER_URL}/api/user_records") as response:
if response.status == 200:
data = await response.json()
return data
else:
print(f"Failed to fetch user records. HTTP Status: {response.status}")
return None
# Fetch GitHub username from web server
async def fetch_github_username(member):
async with aiohttp.ClientSession() as session:
async with session.get(f"{WEB_SERVER_URL}/api/github/username/{member.id}") as response:
if response.status == 200:
data = await response.json()
return data.get('github_username')
else:
print(f"Failed to fetch GitHub username for {member.name}. HTTP Status: {response.status}")
return None
# Check if GitHub username is a contributor
async def check_github_contributor(github_username):
async with aiohttp.ClientSession() as session:
async with session.get(f"https://api.github.com/repos/{GITHUB_REPO_OWNER}/{GITHUB_REPO_NAME}/contributors") as response:
if response.status == 200:
contributors = await response.json()
return any(contributor['login'] == github_username for contributor in contributors)
else:
print(f"Failed to check GitHub contributors. HTTP Status: {response.status}")
return False
# Handle contributor role assignment
async def handle_contributor(member, github_username):
user_records = await fetch_user_records()
contribution_status = user_records.get(github_username, {}).get('contributor', False)
if contribution_status:
try:
await member.send(f"Your GitHub username has been updated to {github_username} and you have been given the Contributor role.")
await member.edit(nick=github_username)
role = discord.utils.get(member.guild.roles, id=CONTRIBUTOR_ROLE_ID)
if role:
await member.add_roles(role)
else:
print(f"Contributor role with ID {CONTRIBUTOR_ROLE_ID} not found.")
except discord.Forbidden:
print(f"Failed to DM {member.name}. They may have DMs disabled.")
except Exception as e:
print(f"Failed to handle contributor for {member.name}. Error: {e}")
# Event when a user joins the server
@bot.event
async def on_member_join(member):
if member.guild.id != GUILD_ID:
return
print(f"New member joined: {member.name}")
# Send DM to new member asking them to link their GitHub account
try:
await member.send(
f"Welcome to the server, {member.name}! Please link your GitHub account to get the Contributor role. "
f"Click this link to authorize: {AUTHORIZATION_URL}"
)
print(f"DM sent to {member.name}")
except discord.Forbidden:
print(f"Failed to DM {member.name}. They may have DMs disabled.")
# Command to update all users in the server
@bot.command()
@commands.has_role(ADMIN_ROLE_ID)
async def update_all_users(ctx):
if ctx.guild.id != GUILD_ID:
return
print(f"Updating all users in the server...")
user_records = await fetch_user_records()
for member in ctx.guild.members:
if not member.bot:
try:
github_username = await fetch_github_username(member)
if github_username:
is_contributor = await check_github_contributor(github_username)
if is_contributor:
await handle_contributor(member, github_username)
else:
await member.send(
f"Hi {member.name}, it looks like your GitHub account is not linked as a contributor to the repository. "
f"Please check your GitHub account or link it again. Click this link to authorize: {AUTHORIZATION_URL}"
)
else:
await member.send(
f"Hi {member.name}, we couldn't find your GitHub username. Please link your GitHub account to get the Contributor role. "
f"Click this link to authorize: {AUTHORIZATION_URL}"
)
except discord.Forbidden:
print(f"Failed to DM {member.name}. They may have DMs disabled.")
except Exception as e:
print(f"An error occurred with user {member.name}: {e}")
await ctx.send("All users have been updated.")
# Command to update specific users
@bot.command()
@commands.has_role(ADMIN_ROLE_ID)
async def update_users(ctx, *user_ids: int):
if ctx.guild.id != GUILD_ID:
return
print(f"Updating specific users...")
# user_records = await fetch_user_records()
for user_id in user_ids:
member = ctx.guild.get_member(user_id)
if member:
github_username = await fetch_github_username(member)
if github_username:
is_contributor = await check_github_contributor(github_username)
if is_contributor:
await handle_contributor(member, github_username)
else:
await member.send(
f"Hi {member.name}, we couldn't find your GitHub username. Please link your GitHub account to get the Contributor role. "
f"Click this link to authorize: {AUTHORIZATION_URL}"
)
else:
await ctx.send(f"User with ID {user_id} not found in the guild.")
await ctx.send("Specific users have been updated.")
# Command to send a button for updating roles
@bot.command()
@commands.has_role(ADMIN_ROLE_ID)
async def send_update_button(ctx):
if ctx.guild.id != GUILD_ID:
return
view = discord.ui.View(timeout=180)
Button = discord.ui.Button(style=discord.ButtonStyle.primary, label="Update Roles", custom_id="update_roles")
async def Callback(interaction: discord.Interaction):
await interaction.response.send_message("Roles are being updated...", ephemeral=True)
await update_all_users(interaction.message.channel)
Button.callback = Callback
view.add_item(Button)
await ctx.send(
"Click the button below to update roles for users.",
view=view
)
"""
# Button interaction handler
@bot.event
async def on_interaction(interaction):
if interaction.type == discord.InteractionType.component:
if interaction.custom_id == "update_roles":
if not any(role.id == ADMIN_ROLE_ID for role in interaction.user.roles):
await interaction.response.send_message("You do not have permission to use this button.", ephemeral=True)
return
await interaction.response.send_message("Updating roles...", ephemeral=True)
"""
# Error handler for the update_all_users command
@update_all_users.error
async def update_all_users_error(ctx, error):
if isinstance(error, commands.CheckFailure):
await ctx.send("You do not have permission to use this command.")
else:
await ctx.send(f"An error occurred: {error}")
# Error handler for the update_users command
@update_users.error
async def update_users_error(ctx, error):
await ctx.send(f"An error occurred: {error}")
if __name__ == "__main__":
bot.run(TOKEN)