-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.py
More file actions
182 lines (139 loc) · 5.84 KB
/
bot.py
File metadata and controls
182 lines (139 loc) · 5.84 KB
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
import logging
import asyncio
import re
import sqlite3
from pathlib import Path
import discord
from discord import app_commands
import yaml
import troubleshoot
import doc_command
import quick_reply
log = logging.getLogger("toolscreen-bot")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
ROOT = Path(__file__).resolve().parent
config = yaml.safe_load(open(ROOT / "config.yaml", encoding="utf-8"))
BOT_TOKEN: str = config["bot_token"]
WATCHED: set[int] = set(config.get("watched_channel_ids", []))
TRIAGE_DELAY: int = config.get("triage_delay_seconds", 2)
TAG_BUG: str = config.get("bug_tag_name", "Bug").lower()
TAG_ONGOING: str = config.get("ongoing_tag_name", "Ongoing").lower()
DEV_ROLE_ID: int = config.get("dev_role_id", 0)
DEFAULT_TRIAGE = """\
Hey @MENTION, check <#1475303077342085121> first, your issue might already be solved!
If not, please tell us:
• your Toolscreen version
• what happened (what you did, what you expected, what you got instead)
• your Toolscreen log file, found at `C:\\Users\\<your username>\\.config\\toolscreen\\logs\\latest.log`"""
DB = ROOT / "bot.db"
_conn = sqlite3.connect(DB)
_conn.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
_conn.commit()
def db_get(key: str, default: str | None = None) -> str | None:
row = _conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
return row[0] if row else default
def db_set(key: str, value: str):
_conn.execute("INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value))
_conn.commit()
def find_tag(channel: discord.ForumChannel, name: str) -> discord.ForumTag | None:
return next((t for t in channel.available_tags if t.name.lower() == name), None)
def has_tag(thread: discord.Thread, name: str) -> bool:
return any(t.name.lower() == name for t in thread.applied_tags)
async def set_tag(thread: discord.Thread, tag: discord.ForumTag) -> bool:
if tag.id in {t.id for t in thread.applied_tags}:
return False
tags = (list(thread.applied_tags) + [tag])[:5]
try:
await thread.edit(applied_tags=tags)
return True
except discord.HTTPException as e:
log.error("Tag add failed on %s: %s", thread.id, e)
return False
intents = discord.Intents.default()
intents.guilds = True
intents.guild_messages = True
intents.message_content = True
_REACTIONS = [
(re.compile(r"(?i)this is tool(\s|$)"), discord.PartialEmoji(name="tool", id=1474158956606652708)),
(re.compile(r"(?i)this is screen(\s|$)"), discord.PartialEmoji(name="screen", id=1474159046645780737)),
]
SUGGESTIONS_CH = 1479222344370360320
_VOTE_EMOJIS = [
discord.PartialEmoji(name="upvote", id=1484192539090358383),
discord.PartialEmoji(name="downvote", id=1484192538125402233),
]
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
troubleshoot.load_tree()
troubleshoot.setup(client, tree)
doc_command.setup(client, tree)
quick_reply.setup(config)
def _has_dev_role(interaction: discord.Interaction) -> bool:
if not DEV_ROLE_ID or not interaction.guild:
return False
return any(r.id == DEV_ROLE_ID for r in interaction.user.roles)
@tree.command(name="bugform", description="Set the bug triage message")
@app_commands.describe(message="New message (use \\n for newlines)")
async def cmd_bugform(interaction: discord.Interaction, message: str):
if not _has_dev_role(interaction):
await interaction.response.send_message("Missing permissions.", ephemeral=True)
return
text = message.replace("\\n", "\n")
db_set("triage_message", text)
log.info("Triage updated by %s", interaction.user)
await interaction.response.send_message(f"Updated.\n>>> {text[:500]}", ephemeral=True)
@tree.command(name="bugform-reset", description="Reset bug triage to default")
async def cmd_bugform_reset(interaction: discord.Interaction):
if not _has_dev_role(interaction):
await interaction.response.send_message("Missing permissions.", ephemeral=True)
return
db_set("triage_message", DEFAULT_TRIAGE)
log.info("Triage reset by %s", interaction.user)
await interaction.response.send_message("Reset to default.", ephemeral=True)
@client.event
async def on_ready():
log.info("Online as %s", client.user)
cmds = await tree.sync()
log.info("Synced %d global commands", len(cmds))
@client.event
async def on_message(message: discord.Message):
if message.author == client.user:
return
rule = await quick_reply.match(message)
if rule:
try:
await message.reply(embed=quick_reply.build_embed(rule), mention_author=False)
except discord.HTTPException as e:
log.error("Quick reply failed: %s", e)
if message.channel.id == SUGGESTIONS_CH:
for emoji in _VOTE_EMOJIS:
try:
await message.add_reaction(emoji)
except discord.HTTPException:
pass
for pattern, emoji in _REACTIONS:
if pattern.search(message.content):
try:
await message.add_reaction(emoji)
except discord.HTTPException:
pass
@client.event
async def on_thread_create(thread: discord.Thread):
if thread.parent_id not in WATCHED:
return
parent = thread.parent
if not isinstance(parent, discord.ForumChannel):
return
ongoing = find_tag(parent, TAG_ONGOING)
if ongoing:
await set_tag(thread, ongoing)
if not has_tag(thread, TAG_BUG):
return
await asyncio.sleep(TRIAGE_DELAY)
msg = db_get("triage_message", DEFAULT_TRIAGE).replace("@MENTION", f"<@{thread.owner_id}>")
try:
await thread.send(msg)
except discord.HTTPException as e:
log.error("Triage send failed on %s: %s", thread.id, e)
if __name__ == "__main__":
client.run(BOT_TOKEN, log_handler=None)