111 Commits
Author SHA1 Message Date
nyeki ee01d2160d Update tip strings 2026-05-07 23:16:22 -03:00
nyeki 16cbda838e Fix p.help shard display 2026-04-06 17:30:19 -03:00
nyeki ce0cef5db7 Bump version in cargo.roml 2026-04-06 17:25:56 -03:00
nyeki afcfdad13d Add confirmation message to p.rh 2026-04-06 17:20:02 -03:00
nyeki 2823868460 Add shard number to p.help 2026-04-06 17:18:10 -03:00
nyeki 78fcfe386d Add p.rh command 2026-04-06 17:11:08 -03:00
nyeki 5fdea76f37 Fix more linter warnings 2026-04-03 06:02:50 -03:00
nyeki 6248dc72f0 Fix some linting warningss 2026-04-03 06:01:48 -03:00
nyeki 53e066f868 Add exception to on call message event handler 2026-04-03 05:58:50 -03:00
nyeki c9b81219e5 Make exception for bot owner in NonNewAccountPermission 2026-04-03 05:57:35 -03:00
nyeki b0a6950005 Version bump 2026-03-09 01:20:13 -03:00
nyeki 658dbd9c8d Remove quotes from lyrics on Payphone's status 2026-03-09 01:13:53 -03:00
nyeki 275bfa440c Censor usernames on call 2026-03-09 01:08:11 -03:00
nyeki 943225ce1f Version bump 2026-03-07 20:24:02 -03:00
nyeki e6b99759ce Make p.co and p.d reply to the user 2026-03-07 20:15:25 -03:00
nyeki 014acf55c6 Add Command trait method documentation and other docstrings, make p.co and p.d commands be used from the middle of a message 2026-03-07 20:10:27 -03:00
nyeki 769d36e9c2 p.coc -> p.co, remove embeds from p.d and p.co 2026-03-07 19:41:23 -03:00
nyeki 12c6755897 Version bump 2026-03-07 19:34:37 -03:00
nyeki 21678239b5 Checkpoint 2026-03-07 19:27:40 -03:00
nyeki d0b5f86740 Checkpoint 2026-02-26 01:55:07 -03:00
nyeki 70c531ddac Bump version 2026-02-25 22:56:42 -03:00
nyeki 08c4534907 Lyrics status 2026-02-25 22:56:10 -03:00
nyeki 6aee4f39b0 Use propagation message ID to query instead of materialized view 2026-02-25 19:35:54 -03:00
nyeki e7aa3247e5 Update tips 2026-02-19 04:16:25 -03:00
nyeki 5dd8fdcc58 Report bot stats to top.gg 2026-02-15 17:56:35 -03:00
nyeki a0c0c17747 Roll back tips 2026-02-09 00:55:25 -03:00
nyeki 2b3dc00941 Update current amount of funding 2026-02-07 16:15:26 -03:00
nyeki 1c79d4b701 Migrate to MUSL 2026-02-06 21:35:28 -03:00
nyeki 384ca1f4e8 Fix lint warnings in main.rs 2025-11-23 15:41:02 -03:00
nyeki 84ff48ae8c Add teto command 2025-11-23 15:39:50 -03:00
nyeki be5422345b Bring back old tips 2025-10-27 16:21:29 -03:00
nyeki b2297703c8 Replace tips with a request for donations 2025-10-20 20:16:54 -03:00
nyeki e5ecbbfa10 Bump version 2025-09-01 14:00:47 -03:00
nyeki f9a0c8220c Censor "nudes" 2025-09-01 13:20:34 -03:00
nyeki 176280fdf4 Bump version 2025-09-01 05:21:36 -03:00
nyeki 0c3bbf9a03 Censor replies 2025-09-01 05:17:00 -03:00
nyeki 08d71a5e82 Remove some words and phrases from being censored 2025-08-30 16:32:06 -03:00
nyeki 86f2a6bf9c Make sensitive topics only get censored 2025-08-28 02:58:19 -03:00
nyeki d1669003cf Increase scylla CPU limits 2025-08-28 02:24:23 -03:00
nyeki b442be08e2 Disable auto call hangup and check for DB inconsistency in call channels 2025-08-26 13:12:17 -03:00
nyeki eb057e0531 Bump version 2025-08-25 23:32:57 -03:00
nyeki 73010fec3d Do not send empty messages 2025-08-25 20:15:05 -03:00
nyeki 676fdcfd96 Run cargo fmt --all 2025-08-25 20:03:21 -03:00
nyeki e5fe77c287 Bump version 2025-08-25 20:03:11 -03:00
nyeki 28d330b1b2 Fix more clippy warnings 2025-08-25 19:52:14 -03:00
nyeki ec893c0cf7 Fix clippy error 2025-08-25 19:51:55 -03:00
nyeki 16085b4bd8 Fix invalid usernames 2025-08-25 19:50:30 -03:00
nyeki ca1ce13887 Bump version 2025-08-25 19:36:43 -03:00
nyeki e44ab51adf Add ban command 2025-08-25 19:36:18 -03:00
nyeki 6d8217ed81 Expire calls where one of both parties doesn't talk for 10 minutes. 2025-08-25 18:24:16 -03:00
nyeki a75fd9f092 Add code of conduct button and fix invalid display names 2025-08-24 21:32:59 -03:00
nyeki 0f5f390d68 Add tip when skipping to a not-yet-started call 2025-08-24 20:22:39 -03:00
nyeki c1a2a6a449 Bump version 2025-08-24 20:16:00 -03:00
nyeki 82fba989a4 Attempt to patch "Call not found" errors 2025-08-24 20:06:09 -03:00
nyeki 3f5ec4f258 Add colors update 2025-08-24 20:03:52 -03:00
nyeki 39120a65fa Add links to reply embeds and fix nitro custom server avatars not displaying 2025-08-24 15:45:54 -03:00
nyeki fc9bbcc87c Make all avatars use PNG instead of WEBP 2025-08-24 13:06:37 -03:00
nyeki 497d180669 Add hidden feature to not send messages when they're preceeded by an X 2025-08-24 03:51:08 -03:00
nyeki bd09a55a74 Make mask command not toggle the mask status when neither on nor off are passed 2025-08-24 03:42:37 -03:00
nyeki 14a6037101 Go back one patch version, let's make the masks version rounded 2025-08-24 02:05:41 -03:00
nyeki b9dbc17b63 Bump Payphone version and make ansible Payphone deployment playbook bump version at the end, not at the beginning 2025-08-24 02:04:51 -03:00
nyeki 325b4cbc16 Add support for masks 2025-08-24 02:02:25 -03:00
nyeki 2a2ffd8894 Restrict accounts to min 30 days to be able to call and start working on masks 2025-08-23 19:56:50 -03:00
nyeki 134d4e8879 Bump version 2025-08-23 16:43:59 -03:00
nyeki 291c4d50b2 Attempt to make invalid nicknames valid 2025-08-23 16:43:52 -03:00
nyeki 06faca7aa2 Bump version and reformat stats command 2025-08-23 14:51:35 -03:00
nyeki 8e9a23b4d9 Bump version 2025-08-23 13:34:25 -03:00
nyeki 8f6d28f3b6 Register statistics command 2025-08-23 13:34:18 -03:00
nyeki 35f3504c00 Add statistics command 2025-08-23 13:28:52 -03:00
nyeki 6c72c27911 Remove sexually explicit typos rule and add migration for masked call participants 2025-08-23 13:22:35 -03:00
nyeki 7d47a9eb35 Start working on mask command 2025-08-23 12:16:06 -03:00
nyeki b10484cacc Add user argument docs to incidents command 2025-08-23 03:23:01 -03:00
nyeki 7a5943a5ef Add automod in development and request for donations tips 2025-08-23 03:09:07 -03:00
nyeki 8294fafeba Disable expire incident button when the incident has already expired 2025-08-23 02:19:05 -03:00
nyeki c5d699292f Add fast forward pagination buttons to incidents command 2025-08-23 02:15:40 -03:00
nyeki 679096a685 Add expire ban button to incidents command 2025-08-23 02:11:23 -03:00
nyeki 9b70714fe3 Make reply embeds say "Replying to ..." 2025-08-23 01:30:54 -03:00
nyeki 6df7fd272f Fix call skipping message 2025-08-23 01:17:02 -03:00
nyeki d0aa3d72d5 Fix incorrect "created by ID" value in incidents 2025-08-23 00:09:48 -03:00
nyeki b108d93c55 Sort incidents 2025-08-23 00:03:30 -03:00
nyeki eaa38f3474 Add basic moderator commands 2025-08-23 00:02:10 -03:00
nyeki 8868b18be3 Add support for extras, conditionally displaying commands in the help command, and start working on moderation commands 2025-08-22 18:06:52 -03:00
nyeki 55ae1c8937 Set bot status 2025-08-21 22:05:58 -03:00
nyeki 5e3201e7c5 Add support for presence to the framework 2025-08-21 21:59:37 -03:00
nyeki 7d19e928d6 Add plurals for slurs 2025-08-21 20:16:42 -03:00
nyeki c88496a73a Bump version 2025-08-21 20:09:18 -03:00
nyeki aa32abfa90 Fix reversed leaderboard 2025-08-21 20:06:59 -03:00
nyeki 6c240cfece Bump version and remove migrate copying command from Dockerfile 2025-08-21 19:22:44 -03:00
nyeki 1f9f094445 Bump version 2025-08-21 19:20:05 -03:00
nyeki e28f11d9bb Make permissions checking not depend on the cache 2025-08-21 19:19:02 -03:00
nyeki 408f0223a2 Update user's name when running commands or on call 2025-08-21 18:59:43 -03:00
nyeki 2b1a738379 Add strings to call commands 2025-08-21 18:57:30 -03:00
nyeki cca77aa4a7 Add call message strings 2025-08-21 02:25:31 -03:00
nyeki a92a02484c Add Redis connection URL to ansible playbook for Payphone 2025-08-21 02:15:44 -03:00
nyeki 0318f002fc Add leaderboard command and XP winning system 2025-08-21 02:14:56 -03:00
nyeki 4563c49245 Remove trace logs for webhook recreation 2025-08-20 23:22:18 -03:00
nyeki aba11cb2da Recreate webhooks when they go missing, reuse older webhooks, and initiate connections to Redis cluster 2025-08-20 23:20:21 -03:00
nyeki ee49b0a984 Add permission checks to p.prefix command 2025-08-20 02:29:40 -03:00
nyeki 3cc37cfc0c Add more censored phrases 2025-08-19 14:41:44 -03:00
nyeki f785413696 Bump version 2025-08-19 00:18:14 -03:00
nyeki cddda58aca Make permissions checking and notification separate functions 2025-08-18 23:45:52 -03:00
nyeki 0af585cf9e Move huzz to mild swear words 2025-08-18 23:45:32 -03:00
nyeki b6242f5a10 Remove "damn" from censor lists 2025-08-18 22:53:22 -03:00
nyeki 9799631b7c Move words from categories 2025-08-18 22:28:24 -03:00
nyeki 1678eedf6d Bump version 2025-08-18 22:19:59 -03:00
nyeki a6255290b2 Add explicit sexual language typos rule 2025-08-18 22:14:55 -03:00
nyeki 118dacff20 Add whitelisting support 2025-08-18 22:08:42 -03:00
nyeki a994c86f98 Add support for banned word exceptions 2025-08-18 22:04:46 -03:00
nyeki 23969006c2 chore: Release payphone version 4.0.9 2025-08-18 21:11:37 -03:00
nyeki a0f592e66f chore: Release payphone version 4.0.9 2025-08-18 21:10:57 -03:00
nyeki 5ebbfe6458 chore: Release payphone version 4.0.9 2025-08-18 21:07:54 -03:00
102 changed files with 7072 additions and 1697 deletions
Generated
+1159 -45
View File
File diff suppressed because it is too large Load Diff
+28 -5
View File
@@ -1,17 +1,21 @@
[package]
name = "payphone"
version = "4.0.8"
version = "4.4.52"
edition = "2024"
default-run = "payphone"
[dependencies]
anyhow = "1.0.99"
async-trait = "0.1.88"
axum = "0.8.4"
clap = { version = "4.5.42", features = ["derive", "env", "string"] }
color-thief = "0.2.2"
colored = "3.0.0"
csv = "1.3.1"
deadpool-redis = "0.22.0"
deadpool-redis = { version = "0.22.0", features = ["cluster", "cluster-async"] }
dotenvy = "0.15.7"
humantime = "2.2.0"
image = "0.25.6"
include_dir = "0.7.4"
itertools = "0.14.0"
linkify = "0.10.0"
@@ -22,17 +26,36 @@ open = "5.3.2"
rand = "0.9.2"
rand_chacha = { version = "0.9.0", features = ["os_rng"] }
regex = "1.11.1"
reqwest = { version = "0.12.23", features = [
"gzip",
"brotli",
"zstd",
"native-tls-vendored",
] }
rgb = "0.8.52"
scc = "2.3.4"
scylla = { version = "1.3.1", features = ["time-03"] }
serde = { version = "1.0.219", features = ["derive"] }
serde_json = "1.0.143"
thiserror = "2.0.12"
time = { version = "0.3.41", features = ["formatting", "local-offset", "macros"] }
time = { version = "0.3.41", features = [
"formatting",
"local-offset",
"macros",
] }
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread"] }
topgg = { version = "1.4.2", features = ["twilight"] }
tower-http = { version = "0.6.6", features = ["fs"] }
twilight-cache-inmemory = { version = "0.16.0", features = [
"permission-calculator",
] }
twilight-gateway = "0.16.0"
twilight-http = { version = "0.16.0", features = ["simd-json"] }
twilight-model = "0.16.0"
twilight-util = { version = "0.16.0", features = ["builder"] }
twilight-util = { version = "0.16.0", features = [
"builder",
"permission-calculator",
"snowflake",
] }
twilight-validate = "0.16.0"
unicode-segmentation = "1.12.0"
unidecode = "0.3.0"
+17 -9
View File
@@ -1,20 +1,28 @@
FROM rust:latest AS builder
# --- Builder stage ---
FROM rust:1-bookworm AS builder
# Install musl target and musl-tools
RUN rustup target add x86_64-unknown-linux-musl \
&& apt-get update \
&& apt-get install -y musl-tools build-essential
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY . .
RUN cargo build --release
# Build fully static binary
RUN cargo build --release --target x86_64-unknown-linux-musl
# --- Final stage ---
FROM debian:bookworm
COPY --from=builder /app/target/release/payphone /usr/local/bin/payphone
COPY --from=builder /app/target/release/migrate /usr/local/bin/migrate
# Copy static binary
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/payphone /usr/local/bin/payphone
RUN apt-get update && apt-get install -y ca-certificates
RUN update-ca-certificates
RUN apt-get update && apt-get install -y ca-certificates \
&& update-ca-certificates \
&& rm -rf /var/lib/apt/lists/*
ENTRYPOINT [ "/usr/local/bin/payphone" ]
CMD [ "start" ]
ENTRYPOINT ["/usr/local/bin/payphone"]
CMD ["start"]
+66
View File
@@ -31,6 +31,66 @@ services:
scylla-net:
ipv4_address: 172.20.0.4
redis-node-1:
image: redis:latest
container_name: redis-node-1
command: redis-server --port 7000 --cluster-enabled yes --cluster-config-file nodes.conf --appendonly yes
ports:
- "7000:7000"
healthcheck:
test: ["CMD", "redis-cli", "-p", "7000", "ping"]
interval: 5s
timeout: 3s
retries: 5
networks:
redis-net:
ipv4_address: 172.20.1.2
redis-node-2:
image: redis:latest
container_name: redis-node-2
command: redis-server --port 7001 --cluster-enabled yes --cluster-config-file nodes.conf --appendonly yes
ports:
- "7001:7001"
healthcheck:
test: ["CMD", "redis-cli", "-p", "7001", "ping"]
interval: 5s
timeout: 3s
retries: 5
networks:
redis-net:
ipv4_address: 172.20.1.3
redis-node-3:
image: redis:latest
container_name: redis-node-3
command: redis-server --port 7002 --cluster-enabled yes --cluster-config-file nodes.conf --appendonly yes
ports:
- "7002:7002"
healthcheck:
test: ["CMD", "redis-cli", "-p", "7002", "ping"]
interval: 5s
timeout: 3s
retries: 5
networks:
redis-net:
ipv4_address: 172.20.1.4
redis-init:
image: redis:latest
container_name: redis-init
command: redis-cli --cluster create 172.20.1.2:7000 172.20.1.3:7001 172.20.1.4:7002 --cluster-replicas 0 --cluster-yes
restart: no
depends_on:
redis-node-1:
condition: service_healthy
redis-node-2:
condition: service_healthy
redis-node-3:
condition: service_healthy
networks:
- redis-net
volumes:
scylla-data-1:
scylla-data-2:
@@ -42,3 +102,9 @@ networks:
ipam:
config:
- subnet: 172.20.0.0/24
redis-net:
driver: bridge
ipam:
config:
- subnet: 172.20.1.0/24
+25
View File
@@ -0,0 +1,25 @@
apiVersion: v1
kind: Namespace
metadata:
name: redis
---
apiVersion: v1
kind: ConfigMap
metadata:
name: redis-config
namespace: redis
data:
update-node.sh: |
#!/bin/sh
REDIS_NODES="/data/nodes.conf"
sed -i -e "/myself/ s/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/${POD_IP}/" ${REDIS_NODES}
exec "$@"
redis.conf: |+
cluster-enabled yes
cluster-require-full-coverage no
cluster-node-timeout 15000
cluster-config-file /data/nodes.conf
cluster-migration-barrier 1
save ""
appendonly no
protected-mode no
+51
View File
@@ -0,0 +1,51 @@
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: redis-cluster
namespace: redis
spec:
serviceName: redis-cluster
replicas: 6
selector:
matchLabels:
app: redis-cluster
template:
metadata:
labels:
app: redis-cluster
spec:
containers:
- name: redis
image: redis:alpine
ports:
- containerPort: 6379
name: client
- containerPort: 16379
name: gossip
command: ["/conf/update-node.sh", "redis-server", "/conf/redis.conf"]
env:
- name: POD_IP
valueFrom:
fieldRef:
fieldPath: status.podIP
volumeMounts:
- name: conf
mountPath: /conf
readOnly: false
- name: data
mountPath: /data
readOnly: false
volumes:
- name: conf
configMap:
name: redis-config
defaultMode: 0755
volumeClaimTemplates:
- metadata:
name: data
spec:
storageClassName: local-path
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
+16
View File
@@ -0,0 +1,16 @@
apiVersion: v1
kind: Service
metadata:
name: redis-cluster
namespace: redis
spec:
type: ClusterIP
ports:
- port: 6379
targetPort: 6379
name: client
- port: 16379
targetPort: 16379
name: gossip
selector:
app: redis-cluster
+6 -6
View File
@@ -30,10 +30,10 @@ spec:
storageClassName: scylladb-local-xfs
resources:
requests:
cpu: 1
cpu: 2
memory: 8Gi
limits:
cpu: 1
cpu: 2
memory: 8Gi
placement:
nodeAffinity:
@@ -61,10 +61,10 @@ spec:
storageClassName: scylladb-local-xfs
resources:
requests:
cpu: 1
cpu: 2
memory: 8Gi
limits:
cpu: 1
cpu: 2
memory: 8Gi
placement:
nodeAffinity:
@@ -92,10 +92,10 @@ spec:
storageClassName: scylladb-local-xfs
resources:
requests:
cpu: 1
cpu: 2
memory: 8Gi
limits:
cpu: 1
cpu: 2
memory: 8Gi
placement:
nodeAffinity:
+2 -1
View File
@@ -8,4 +8,5 @@ uv run ansible-playbook -i inventory.ini playbooks/04-prometheus-operator.yml
uv run ansible-playbook -i inventory.ini playbooks/05-scylla-operator.yml
uv run ansible-playbook -i inventory.ini playbooks/06-scylla-cluster.yml
uv run ansible-playbook -i inventory.ini playbooks/07-scylla-manager.yml
uv run ansible-playbook -i inventory.ini playbooks/08-payphone.yml --vault-password-file playbooks/00-vault-pwd.txt
uv run ansible-playbook -i inventory.ini playbooks/08-redis.yml
uv run ansible-playbook -i inventory.ini playbooks/09-payphone.yml --vault-password-file playbooks/00-vault-pwd.txt
+23 -13
View File
@@ -1,14 +1,24 @@
$ANSIBLE_VAULT;1.1;AES256
31353838363564633532353539313763643561396661313030346466653839663931323961663362
6333376338336336346562643136316439393962356236640a653836643066346564663363633364
30616634363430646335663339613333616334393037333065336664396338346135353239346261
3366303231616166300a613566643231303066373266646665343637353364303939346464323633
37623565643063353435376238326564353563653735393164616136373531356135666337353765
39326463633965383463353335306432326433313132373461633666343934616638346666306339
36313561363965663662313163663362333466663135363731643737386466643134396564353439
32313936316432313433336235643337386430633434363764666439386234323933313465306638
65396532396533303662326338376661343962613432393735356130613165626465656464343434
63646265333064623735646161656236623366623265626664313564316665396331616631613536
38646264656563353934383237626534663563666335666430326562303862616461343935393737
62343637336563383864383732303861633634303061376666353231323331643538333633643762
35623539303562643763336232353633666661626539356465383631336261363532
30363364303339383037643864396632306537333737383933363164663838333364323837633838
3561323032663461663834613634633734636333306638380a396436646332373330393931396530
36353439343736656432333437653764653132393364626136396230623038626330313366386263
3630663539303665340a623961656435373337363534363863353934326336653361663538616664
36313865646530346633626639393739653131313835383631613833393832396434633038343639
62656236326662343236303133306137653533633064626161636165646164646165653534633036
63623863353438616237323530383033366138656665613331666532316562336232353239323535
33326237653463663862383266373534343434383765303237613436643439313233396338376134
65303161313930383165636133616236386435663232313531633461383938326131353930353761
35303238333863666137313330336366623536613230353639666133333633353566303131393666
32313964636138343632373064366166333134343437613937303538613834623934623161626261
63303832663438356331363534316230613561613961306561376432646132663733303366393961
64373166633938633730643339646433623235306161386338316330336264623031363365376634
38306639356236383464653038663732653465626265663939643234306563346330336139373235
36616662313139356139363532633664333762623235326237636339323039373131666162613930
63336161396635646565393565373736616431643830366163356532383034396636323163623836
37613632343563363032303133333930653431343039633239306561303266393861366134643734
66326534343464363634383461326330346432613266653066643139636232656638346635343130
61383336623763353034316238313536336261616433356461666537633665636430393139663465
61643066356466646264616562343939616336343935663939313537356237303264303761376139
34623231623264633934363537643132643336313633663430643265633564646363623130396437
61383763396633663439626661333630373662616633353232356165663034336131343666643633
373138346631323465303932633962613234
+56
View File
@@ -0,0 +1,56 @@
- name: Set Up Redis Cluster
hosts: init
become: true
tasks:
- name: Create Redis Config Map
kubernetes.core.k8s:
state: present
src: /tmp/k8s/redis/01-config-map.yml
kubeconfig: /etc/rancher/k3s/k3s.yaml
- name: Create Redis Nodes
kubernetes.core.k8s:
state: present
src: /tmp/k8s/redis/02-redis.yml
kubeconfig: /etc/rancher/k3s/k3s.yaml
- name: Wait for Redis Nodes
ansible.builtin.command:
kubectl -n=redis rollout status --timeout=10m sts/redis-cluster
changed_when: false
- name: Create ClusterIP Service
kubernetes.core.k8s:
state: present
src: /tmp/k8s/redis/03-cluster-ip.yml
kubeconfig: /etc/rancher/k3s/k3s.yaml
- name: Grab Node IPs
ansible.builtin.shell:
echo $(kubectl get pods -l app=redis-cluster -n redis -o json | jq -r '.items | map(.status.podIP) | join(":6379 ")'):6379
args:
executable: /bin/bash
register: redis_node_ips
changed_when: false
tags:
- skip_ansible_lint
- name: Display Node IPs
ansible.builtin.debug:
msg: "{{ redis_node_ips.stdout }}"
- name: Check if Redis cluster is already active
ansible.builtin.shell: >
set -o pipefail
kubectl exec redis-cluster-0 -n redis -- redis-cli -p 6379 cluster info | grep cluster_state
args:
executable: /bin/bash
register: redis_cluster_state
changed_when: false
failed_when: false
- name: Activate Redis Cluster
ansible.builtin.shell: >
kubectl exec redis-cluster-0 -n redis -- redis-cli --cluster create --cluster-replicas 1 {{ redis_node_ips.stdout }} --cluster-yes
when: "'cluster_state:ok' not in redis_cluster_state.stdout"
changed_when: false
@@ -49,6 +49,7 @@
type: Opaque
stringData:
PAYPHONE_TOKEN: "{{ bot_token }}"
PAYPHONE_TOPGG_TOKEN: "{{ topgg_token }}"
kubeconfig: /etc/rancher/k3s/k3s.yaml
- name: Set Git credentials
@@ -92,11 +93,15 @@
"--shard",
"$(SHARD_ID):$(SHARD_COUNT)",
"--database-addr",
"scylladb-client.scylla.svc.cluster.local",
"scylladb-client.scylla",
"--database-username",
"cassandra",
"--database-password",
"cassandra"
"cassandra",
"--redis-urls",
"redis://redis-cluster.redis",
"--bot-owner-id",
"1486270291410817114"
]
envFrom:
- secretRef:
@@ -123,3 +128,12 @@
ansible.builtin.command:
kubectl set image -n payphone sts/payphone payphone=registry.nyeki.dev/payphone/payphone:{{ hostvars['localhost'].app_version }}
changed_when: false
- name: Bump Payphone Version
hosts: localhost
gather_facts: true
tasks:
- name: Bump Version
ansible.builtin.shell: >
cargo set-version --bump patch
changed_when: false
+14
View File
@@ -0,0 +1,14 @@
- name: APT Update
hosts: all
become: true
tasks:
- name: Update APT package index
ansible.builtin.apt:
update_cache: yes
cache_valid_time: 3600
- name: Upgrade APT packages
ansible.builtin.apt:
upgrade: dist
autoremove: yes
autoclean: yes
Executable
+1
View File
@@ -0,0 +1 @@
uv run ansible-playbook -i inventory.ini playbooks/09-payphone.yml --vault-password-file playbooks/00-vault-pwd.txt
+2
View File
@@ -0,0 +1,2 @@
group_imports = "StdExternalCrate"
imports_granularity = "Module"
-432
View File
@@ -1,432 +0,0 @@
use std::{collections::HashMap, sync::Arc};
use clap::Parser;
use payphone::{
database::{
self,
models::{
MessageData, Report as PayphoneReport, ReportResolution, Server as PayphoneServer,
UserIncident, UserIncidentType,
},
},
utils::{Bye, get_random_u64, u64_to_i64},
};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use tokio::{sync::Semaphore, time::Instant};
#[derive(Parser)]
struct Args {
dir: String,
#[arg(long, default_value_t = String::from("127.0.0.1"))]
database_addr: String,
#[arg(long)]
database_username: Option<String>,
#[arg(long)]
database_password: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Report {
id: u64,
message_id: u64,
message_content: String,
channel_id: u64,
user_id: u64,
created_at: String,
resolved: String,
resolved_at: Option<String>,
resolved_by_id: Option<u64>,
user_avatar_url: String,
user_name: String,
reply_user_name: Option<String>,
reply_message_content: Option<String>,
reply_user_avatar_url: Option<String>,
reply_user_id: Option<u64>,
reported_by_id: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct User {
id: u64,
is_masked: String,
is_moderator: String,
is_supporter_until: String,
warns_count: u64,
bans_count: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Ban {
id: u64,
user_id: u64,
created_at: String,
expires_at: Option<String>,
created_by_id: u64,
expired_by_id: Option<u64>,
report_id: Option<u64>,
reason: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Server {
id: u64,
prefix: String,
language: String,
name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Warn {
id: u64,
user_id: u64,
reason: String,
created_at: String,
created_by_id: u64,
report_id: u64,
}
#[tokio::main]
async fn main() {
let args = Args::parse();
println!("Testing DB connection...");
let db = Arc::new(
database::init(
args.database_addr,
args.database_username,
args.database_password,
)
.await
.expect("Failed to initialize database"),
);
println!("Reading migration file {}/reports.csv", args.dir);
let mut rdr = csv::Reader::from_path(format!("{}/reports.csv", args.dir))
.expect("Failed to open reports file");
let mut reports = Vec::new();
let format = time::format_description::parse(
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond][offset_hour]",
)
.expect("Failed to parse format description");
for result in rdr.deserialize() {
let report: Report = result.expect("Failed to deserialize report");
reports.push(report);
}
println!("Finished reading reports, found {} reports", reports.len());
println!("Reading migration file {}/users.csv", args.dir);
let mut rdr = csv::Reader::from_path(format!("{}/users.csv", args.dir))
.expect("Failed to open users file");
let mut users = HashMap::new();
for result in rdr.deserialize() {
let user: User = result.expect("Failed to deserialize user");
users.insert(user.id, user).bye();
}
println!("Finished reading users, found {} users", users.len());
println!("Reading migration file {}/bans.csv", args.dir);
let mut rdr =
csv::Reader::from_path(format!("{}/bans.csv", args.dir)).expect("Failed to open bans file");
let mut bans = HashMap::new();
for result in rdr.deserialize() {
let ban: Ban = result.expect("Failed to deserialize ban");
bans.insert(ban.id, ban).bye();
}
println!("Finished reading bans, found {} bans", bans.len());
println!("Reading migration file {}/servers.csv", args.dir);
let mut rdr = csv::Reader::from_path(format!("{}/servers.csv", args.dir))
.expect("Failed to open servers file");
let mut servers = HashMap::new();
for result in rdr.deserialize() {
let server: Server = result.expect("Failed to deserialize server");
servers.insert(server.id, server).bye();
}
println!("Finished reading servers, found {} servers", servers.len());
println!("Reading migration file {}/warns.csv", args.dir);
let mut rdr = csv::Reader::from_path(format!("{}/warns.csv", args.dir))
.expect("Failed to open warns file");
let mut warns = HashMap::new();
for result in rdr.deserialize() {
let warn: Warn = result.expect("Failed to deserialize warn");
warns.insert(warn.id, warn).bye();
}
println!("Finished reading warns, found {} warns", warns.len());
println!("Starting migration...");
println!("Inserting server configurations...");
let semaphore = Arc::new(Semaphore::new(50));
let mut tasks = Vec::new();
for (i, server) in servers.values().enumerate() {
let payphone_server = PayphoneServer {
id: server.id,
prefix: server.prefix.clone(),
language: server.language.clone(),
name: server.name.clone(),
};
let task_db = db.clone();
let task_semaphore = semaphore.clone();
tasks.push(tokio::spawn(async move {
let _permit = task_semaphore.acquire().await;
let start = Instant::now();
payphone_server
.insert(&task_db)
.await
.expect("Failed to insert server");
let duration = start.elapsed();
println!(
"({i}) Inserted server {} in {:?}",
payphone_server.id, duration
);
}));
}
let bans = Arc::new(bans);
let warns = Arc::new(warns);
let reports = Arc::new(reports);
for (i, report) in reports.iter().enumerate() {
let task_db = db.clone();
let task_semaphore = semaphore.clone();
let task_report = report.clone();
let task_bans = bans.clone();
let task_warns = warns.clone();
let task_format = format.clone();
tasks.push(tokio::spawn(async move {
let _permit = task_semaphore.acquire().await;
let start = Instant::now();
let resolution = if task_report.resolved == "t" {
if task_bans.iter().any(|(_id, ban)| {
ban.report_id
.map(|report_id| task_report.id == report_id)
.unwrap_or(false)
}) {
Some(ReportResolution::Ban)
} else if task_warns
.iter()
.any(|(_id, warn)| warn.report_id == task_report.id)
{
Some(ReportResolution::Warn)
} else {
Some(ReportResolution::Skip)
}
} else {
None
};
let payphone_report = PayphoneReport {
id: task_report.id,
user_id: task_report.user_id,
message: MessageData {
id: u64_to_i64(task_report.message_id),
call_id: 0,
author_id: u64_to_i64(task_report.user_id),
author_name: task_report.user_name,
author_avatar_url: task_report.user_avatar_url,
author_mask: None,
content: task_report.message_content,
attachments: vec![],
sticker: None,
propagation_message_id: None,
propagation_channel_id: None,
replying_to_message_id: None,
is_deleted: false,
is_edited: false,
is_censored: false,
},
created_at: OffsetDateTime::parse(&task_report.created_at, &task_format)
.expect("Failed to parse created_at")
.to_utc(),
created_by_ids: task_report
.reported_by_id
.map(|id| vec![id])
.unwrap_or_default(),
replying_to: None,
reviewed_at: task_report.resolved_at.as_ref().map(|s| {
OffsetDateTime::parse(s, &task_format)
.expect("Failed to parse resolved_at")
.to_utc()
}),
resolution,
reviewed_by_id: task_report.resolved_by_id,
};
payphone_report
.insert(&task_db)
.await
.expect("Failed to insert report");
let duration = start.elapsed();
println!(
"({i}) Inserted report {} in {:?}",
payphone_report.id, duration
);
}));
}
for (i, ban) in bans.values().enumerate() {
let task_semaphore = semaphore.clone();
let task_format = format.clone();
let task_db = db.clone();
let task_reports = reports.clone();
let task_ban = Arc::new(ban.clone());
tasks.push(tokio::spawn(async move {
let _permit = task_semaphore.acquire().await;
let start = Instant::now();
let message = task_reports
.iter()
.find(|report| {
task_ban
.report_id
.map(|id| id == report.id)
.unwrap_or(false)
})
.map(|report| MessageData {
id: u64_to_i64(report.message_id),
call_id: 0,
author_id: u64_to_i64(report.user_id),
author_name: report.user_name.clone(),
author_avatar_url: report.user_avatar_url.clone(),
author_mask: None,
content: report.message_content.clone(),
attachments: vec![],
sticker: None,
propagation_message_id: None,
propagation_channel_id: None,
replying_to_message_id: None,
is_deleted: false,
is_edited: false,
is_censored: false,
});
let payphone_incident = UserIncident {
incident_id: get_random_u64(),
user_id: task_ban.user_id,
report_id: task_ban.report_id,
r#type: UserIncidentType::Ban,
message,
reason: task_ban.reason.clone(),
created_at: OffsetDateTime::parse(&task_ban.created_at, &task_format)
.expect("Failed to parse created_at")
.to_utc(),
created_by_id: Some(task_ban.created_by_id),
duration: None,
expires_at: task_ban.expires_at.as_ref().map(|expires_at| {
OffsetDateTime::parse(expires_at, &task_format)
.expect("Failed to parse expires_at")
.to_utc()
}),
};
payphone_incident
.insert(&task_db)
.await
.expect("Failed to insert ban");
let duration = start.elapsed();
println!(
"({i}) Inserted incident (ban) {} in {:?}",
payphone_incident.incident_id, duration
);
}));
}
for (i, warn) in warns.values().enumerate() {
let task_semaphore = semaphore.clone();
let task_format = format.clone();
let task_db = db.clone();
let task_reports = reports.clone();
let task_warn = Arc::new(warn.clone());
tasks.push(tokio::spawn(async move {
let _permit = task_semaphore.acquire().await;
let start = Instant::now();
let message = task_reports
.iter()
.find(|report| report.id == task_warn.report_id)
.map(|report| MessageData {
id: u64_to_i64(report.message_id),
call_id: 0,
author_id: u64_to_i64(report.user_id),
author_name: report.user_name.clone(),
author_avatar_url: report.user_avatar_url.clone(),
author_mask: None,
content: report.message_content.clone(),
attachments: vec![],
sticker: None,
propagation_message_id: None,
propagation_channel_id: None,
replying_to_message_id: None,
is_deleted: false,
is_edited: false,
is_censored: false,
});
let payphone_incident = UserIncident {
incident_id: get_random_u64(),
user_id: task_warn.user_id,
report_id: Some(task_warn.report_id),
r#type: UserIncidentType::Warning,
message,
reason: task_warn.reason.clone(),
created_at: OffsetDateTime::parse(&task_warn.created_at, &task_format)
.expect("Failed to parse created_at")
.to_utc(),
created_by_id: Some(task_warn.created_by_id),
duration: None,
expires_at: None,
};
payphone_incident
.insert(&task_db)
.await
.expect("Failed to insert warn");
let duration = start.elapsed();
println!(
"({i}) Inserted incident (warn) {} in {:?}",
payphone_incident.incident_id, duration
);
}));
}
for task in tasks {
task.await.expect("Failed to join task");
}
}
+32 -11
View File
@@ -64,7 +64,9 @@
//! starting the server. You can also use the `--bind` argument to specify the address to bind the
//! server to, which defaults to `0.0.0.0:3000`.
use std::{fmt, net::SocketAddr, str::FromStr};
use std::fmt;
use std::net::SocketAddr;
use std::str::FromStr;
use twilight_gateway::ShardId;
@@ -196,21 +198,14 @@ pub enum Commands {
database_addr: String,
/// The username to use when connecting to the database.
#[arg(
long,
env = "PAYPHONE_DATABASE_USERNAME",
value_name = "USERNAME"
)]
#[arg(long, env = "PAYPHONE_DATABASE_USERNAME", value_name = "USERNAME")]
database_username: Option<String>,
/// The password to use when connecting to the database.
#[arg(
long,
env = "PAYPHONE_DATABASE_PASSWORD",
value_name = "PASSWORD"
)]
#[arg(long, env = "PAYPHONE_DATABASE_PASSWORD", value_name = "PASSWORD")]
database_password: Option<String>,
/// The current shard being run.
#[arg(
long,
short,
@@ -219,6 +214,32 @@ pub enum Commands {
default_value_t = Shard::default())
]
shard: Shard,
/// The Redis URLs to connect to.
#[arg(
long,
env = "PAYPHONE_REDIS_URLS",
value_name = "URLS",
default_values = &["redis://127.0.0.1:6379"],
)]
redis_urls: Vec<String>,
/// The bot owner's ID, this user will be allowed to assign moderators.
#[arg(
long,
env = "PAYPHONE_OWNER_ID",
value_name = "ID",
default_value_t = 0
)]
bot_owner_id: u64,
#[arg(
long,
env = "PAYPHONE_TOPGG_TOKEN",
value_name = "TOKEN",
help = "The token to use for the Top.gg API, used for posting server counts and other stats. If not provided, Top.gg integration will be disabled."
)]
topgg_token: Option<String>,
},
/// Starts a documentation server for the project which serves `cargo doc` and refreshes on
+105
View File
@@ -0,0 +1,105 @@
use std::io::Cursor;
use std::sync::Arc;
use color_thief::ColorFormat;
use image::{GenericImageView, ImageReader};
use reqwest::header::USER_AGENT;
use rgb::Rgb;
use tokio::sync::Semaphore;
use tokio::sync::mpsc::Receiver;
use crate::constants::VERSION;
use crate::database::models::User;
use crate::discord::images::get_user_custom_avatar_url_or_none;
use crate::state::State;
pub struct AvatarColorFetchingRequest {
pub hash: String,
pub user_id: u64,
}
impl AvatarColorFetchingRequest {
pub fn new(hash: impl ToString, user_id: u64) -> Self {
Self {
hash: hash.to_string(),
user_id,
}
}
}
pub fn init_color_fetching_queue_listener(
mut receiver: Receiver<AvatarColorFetchingRequest>,
state: Arc<State>,
) {
tokio::spawn(async move {
let semaphore = Arc::new(Semaphore::new(5));
while let Some(request) = receiver.recv().await {
let task_semaphore = semaphore.clone();
let task_state = state.clone();
tokio::spawn(async move {
let _permit = task_semaphore
.acquire()
.await
.inspect_err(|e| log::error!("Failed to acquire semaphore permit: {e}"))
.expect("Failed to acquire semaphore permit");
let avatar_url = get_user_custom_avatar_url_or_none(request.user_id, request.hash);
let image_bytes = reqwest::Client::new()
.get(avatar_url)
.header(USER_AGENT, format!("Payphone/v{VERSION}"))
.send()
.await
.inspect_err(|e| log::error!("Failed to fetch avatar color: {e}"))?
.error_for_status()?
.bytes()
.await
.inspect_err(|e| log::error!("Failed to read avatar image bytes: {e}"))?;
let color = tokio::task::spawn_blocking(move || {
let img = ImageReader::new(Cursor::new(image_bytes))
.with_guessed_format()?
.decode()?;
let mut pixels = Vec::new();
for (_x, _y, rgba) in img.pixels() {
pixels.extend_from_slice(&rgba.0);
}
drop(img);
let palette = color_thief::get_palette(&pixels, ColorFormat::Rgba, 1, 2)?;
Ok::<_, anyhow::Error>(palette.first().cloned())
})
.await??;
if let Some(color) = color {
let Rgb { r, g, b } = color;
let color_int: u32 = ((r as u32) << 16) | ((g as u32) << 8) | (b as u32);
let mut user = User::get_by_id(request.user_id, &task_state.db)
.await
.inspect_err(|e| {
log::error!("Failed to fetch user to set their new avatar color: {e}")
})?
.ok_or(anyhow::anyhow!(
"User with ID {} not found when fetching their avatar URL color",
request.user_id
))
.inspect_err(|e| log::error!("{e}"))?;
user.color = Some(color_int as i32);
user.insert(&task_state.db).await?;
}
Ok::<_, anyhow::Error>(())
});
}
});
}
+2
View File
@@ -1,5 +1,7 @@
//! Constants used throughout the Payphone project.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
/// The default command prefix used by the bot for new servers.
pub const DEFAULT_PREFIX: &str = "p.";
+1 -1
View File
@@ -144,7 +144,7 @@ CREATE TABLE IF NOT EXISTS payphone.user_incidents (
expires_at TIMESTAMP,
duration ASCII,
PRIMARY KEY (user_id)
PRIMARY KEY (user_id, incident_id)
);
CREATE TABLE IF NOT EXISTS payphone.server_incidents (
@@ -0,0 +1 @@
ALTER TABLE payphone.users ADD is_banned_from_leaderboard BOOLEAN;
@@ -0,0 +1,4 @@
CREATE MATERIALIZED VIEW IF NOT EXISTS payphone.users_by_name AS
SELECT user_id, name FROM payphone.users
WHERE user_id IS NOT NULL AND name IS NOT NULL
PRIMARY KEY (name, user_id);
@@ -0,0 +1,6 @@
ALTER TABLE payphone.participants ADD is_masked BOOLEAN;
CREATE MATERIALIZED VIEW IF NOT EXISTS payphone.participants_by_user_id AS
SELECT user_id, call_id, channel_id FROM payphone.participants
WHERE user_id IS NOT NULL AND call_id IS NOT NULL AND channel_id IS NOT NULL
PRIMARY KEY (user_id, call_id, channel_id);
@@ -0,0 +1,4 @@
CREATE MATERIALIZED VIEW IF NOT EXISTS payphone.messages_by_author_id AS
SELECT call_id, message_id, author_id FROM payphone.messages
WHERE call_id IS NOT NULL AND message_id IS NOT NULL AND author_id IS NOT NULL
PRIMARY KEY (call_id, author_id, message_id);
@@ -0,0 +1 @@
ALTER TABLE payphone.users ADD findings SET<TEXT>;
@@ -0,0 +1,8 @@
ALTER TABLE payphone.users ADD avatar_hash TEXT;
ALTER TABLE payphone.users ADD color INT;
ALTER TABLE payphone.users ADD is_color_set BOOLEAN;
CREATE MATERIALIZED VIEW payphone.users_with_no_color AS
SELECT user_id, avatar_hash, is_color_set FROM payphone.users
WHERE user_id IS NOT NULL AND is_color_set IS NOT NULL
PRIMARY KEY (is_color_set, user_id);
+3 -4
View File
@@ -1,10 +1,9 @@
pub mod models;
use include_dir::{Dir, include_dir};
use scylla::{
client::{session::Session, session_builder::SessionBuilder},
errors::ExecutionError,
};
use scylla::client::session::Session;
use scylla::client::session_builder::SessionBuilder;
use scylla::errors::ExecutionError;
use thiserror::Error;
use time::OffsetDateTime;
+656 -147
View File
File diff suppressed because it is too large Load Diff
+25 -2
View File
@@ -8,15 +8,28 @@ use twilight_model::util::ImageHash;
/// * `hash` - The user's avatar hash (if available).
/// * `user_id` - The user's ID.
/// * `discriminator` - The user's discriminator.
/// * `guild_id` - The guild ID, **only set if the user has Nitro and a custom avatar for the
/// server. Otherwise, even in a server, this is NOT SET**.
///
/// Returns:
/// [`String`] - The URL of the user's avatar.
pub fn get_avatar_url(hash: Option<ImageHash>, user_id: u64, discriminator: u64) -> String {
pub fn get_avatar_url(
hash: Option<ImageHash>,
user_id: u64,
discriminator: u64,
guild_id: Option<u64>,
) -> String {
if let Some(hash) = hash {
if let Some(guild_id) = guild_id {
return format!(
"https://cdn.discordapp.com/guilds/{guild_id}/users/{user_id}/avatars/{hash}.webp?size=256"
);
}
format!("https://cdn.discordapp.com/avatars/{user_id}/{hash}.webp?size=256")
} else {
format!(
"https://cdn.discordapp.com/embed/avatars/{}.png?size=256",
"https://cdn.discordapp.com/embed/avatars/{}.webp?size=256",
match discriminator.to_string().as_str() {
"0" => (user_id >> 22) % 6,
_ => discriminator % 6,
@@ -24,3 +37,13 @@ pub fn get_avatar_url(hash: Option<ImageHash>, user_id: u64, discriminator: u64)
)
}
}
/// Returns the user's avatar URL only if it's custom (i.e. not the default avatar). It doesn't
/// take into account custom per-server avatars, i.e. only the global avatar is returned if any.
///
/// Arguments:
/// * `user_id` - The user's ID.
/// * `hash` - The hex-encoded hash string, if any.
pub fn get_user_custom_avatar_url_or_none(user_id: u64, hash: String) -> String {
format!("https://cdn.discordapp.com/avatars/{user_id}/{hash}.webp?size=256")
}
+5
View File
@@ -0,0 +1,5 @@
use crate::database::models::User;
pub struct Extras {
pub user: User,
}
+317 -164
View File
@@ -1,25 +1,29 @@
use std::{fmt::Debug, sync::Arc};
use std::fmt::Debug;
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use thiserror::Error;
use twilight_gateway::{Event, EventTypeFlags, Intents, Shard, ShardId, StreamExt};
use topgg::Stats;
use twilight_cache_inmemory::{DefaultInMemoryCache, ResourceType};
use twilight_gateway::{ConfigBuilder, Event, EventTypeFlags, Intents, Shard, ShardId, StreamExt};
use twilight_http::Client;
use twilight_model::gateway::payload::outgoing::update_presence::UpdatePresencePayload;
use crate::{
framework::{
commands::{Command, runner::CommandRunner},
events::traits::{
OnInteractionHandler, OnMessageDeleteHandler, OnMessageEditHandler, OnMessageHandler,
OnReadyHandler, OnReconnectHandler, OnServerCreateHandler, OnServerDeleteHandler,
OnServerUpdateHandler,
},
interactions::{
components::Component, registry::ComponentRegistry, runner::InteractionRunner,
},
runtime::Runtime,
},
utils::Bye,
use crate::framework::commands::Command;
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::commands::runner::CommandRunner;
use crate::framework::events::traits::{
OnInteractionHandler, OnMessageDeleteHandler, OnMessageEditHandler, OnMessageHandler,
OnReadyHandler, OnReconnectHandler, OnServerCreateHandler, OnServerDeleteHandler,
OnServerUpdateHandler,
};
use crate::framework::interactions::components::Component;
use crate::framework::interactions::registry::ComponentRegistry;
use crate::framework::interactions::runner::InteractionRunner;
use crate::framework::runtime::Runtime;
use crate::framework::tasks::Task;
use crate::utils::Bye;
/// Errors occurred while attempting to run the bot.
#[derive(Debug, Error)]
@@ -30,7 +34,7 @@ pub enum RuntimeError {
/// Getter trait for command prefixes.
#[async_trait]
pub trait PrefixGetter<T> {
pub trait PrefixGetter<T, E> {
/// Get the command prefixes for the given server and user IDs.
///
/// The getter must never fail. In case an internal process does, it must fall back to default
@@ -47,74 +51,93 @@ pub trait PrefixGetter<T> {
/// first one will always be the safest choice.
async fn get(
&self,
runtime: &Runtime<T>,
runtime: &Runtime<T, E>,
server_id: Option<u64>,
user_id: Option<u64>,
) -> Vec<String>;
}
#[async_trait]
impl<T> PrefixGetter<T> for String {
async fn get(&self, _: &Runtime<T>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
impl<T, E> PrefixGetter<T, E> for String {
async fn get(&self, _: &Runtime<T, E>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
vec![self.to_string()]
}
}
#[async_trait]
impl<T> PrefixGetter<T> for &str {
async fn get(&self, _: &Runtime<T>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
impl<T, E> PrefixGetter<T, E> for &str {
async fn get(&self, _: &Runtime<T, E>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
vec![self.to_string()]
}
}
#[async_trait]
impl<T: Send + Sync + 'static, const N: usize, S: Send + Sync + 'static> PrefixGetter<S> for [T; N]
impl<T, const N: usize, S, E> PrefixGetter<S, E> for [T; N]
where
T: ToString,
T: ToString + Send + Sync + 'static,
E: Send + Sync + 'static,
{
async fn get(&self, _: &Runtime<S>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
async fn get(&self, _: &Runtime<S, E>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
self.iter().map(|s| s.to_string()).collect()
}
}
#[async_trait]
impl<F, Fut, T> PrefixGetter<T> for F
impl<F, Fut, T, E> PrefixGetter<T, E> for F
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Vec<String>> + Send,
E: Send + Sync + 'static,
{
async fn get(&self, _: &Runtime<T>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
async fn get(&self, _: &Runtime<T, E>, _: Option<u64>, _: Option<u64>) -> Vec<String> {
(self)().await
}
}
pub struct Bot<T: Send + Sync = ()> {
pub struct Bot<S: Send + Sync, E: Send + Sync = ()> {
shard: ShardId,
state: Arc<T>,
prefixes: Arc<dyn PrefixGetter<T> + Send + Sync>,
state: Arc<S>,
presence: Option<UpdatePresencePayload>,
prefixes: Arc<dyn PrefixGetter<S, E> + Send + Sync>,
intents: Intents,
commands: Vec<Arc<dyn Command<T>>>,
components: Vec<Arc<dyn Component<T>>>,
on_ready_handlers: Vec<Arc<dyn OnReadyHandler<T>>>,
on_reconnect_handlers: Vec<Arc<dyn OnReconnectHandler<T>>>,
on_interaction_handlers: Vec<Arc<dyn OnInteractionHandler<T>>>,
on_message_handlers: Vec<Arc<dyn OnMessageHandler<T>>>,
on_message_edit_handlers: Vec<Arc<dyn OnMessageEditHandler<T>>>,
on_message_delete_handlers: Vec<Arc<dyn OnMessageDeleteHandler<T>>>,
on_server_create_handlers: Vec<Arc<dyn OnServerCreateHandler<T>>>,
on_server_update_handlers: Vec<Arc<dyn OnServerUpdateHandler<T>>>,
on_server_delete_handlers: Vec<Arc<dyn OnServerDeleteHandler<T>>>,
extras: Arc<dyn ExtrasGetter<S, Extras = E>>,
cached_resource_types: Vec<ResourceType>,
commands: Vec<Arc<dyn Command<S, E>>>,
components: Vec<Arc<dyn Component<S, E>>>,
tasks: Vec<Arc<dyn Task<S, E>>>,
on_ready_handlers: Vec<Arc<dyn OnReadyHandler<S, E>>>,
on_reconnect_handlers: Vec<Arc<dyn OnReconnectHandler<S, E>>>,
on_interaction_handlers: Vec<Arc<dyn OnInteractionHandler<S, E>>>,
on_message_handlers: Vec<Arc<dyn OnMessageHandler<S, E>>>,
on_message_edit_handlers: Vec<Arc<dyn OnMessageEditHandler<S, E>>>,
on_message_delete_handlers: Vec<Arc<dyn OnMessageDeleteHandler<S, E>>>,
on_server_create_handlers: Vec<Arc<dyn OnServerCreateHandler<S, E>>>,
on_server_update_handlers: Vec<Arc<dyn OnServerUpdateHandler<S, E>>>,
on_server_delete_handlers: Vec<Arc<dyn OnServerDeleteHandler<S, E>>>,
topgg_token: Option<String>,
}
impl<T: 'static + Send + Sync> Bot<T> {
pub fn new(state: T, prefixes: impl PrefixGetter<T> + Send + Sync + 'static) -> Self {
impl<T, E> Bot<T, E>
where
T: 'static + Send + Sync,
E: 'static + Send + Sync,
{
pub fn new(
state: Arc<T>,
prefixes: impl PrefixGetter<T, E> + Send + Sync + 'static,
extras: impl ExtrasGetter<T, Extras = E> + 'static,
) -> Self {
Self {
shard: ShardId::new(0, 1),
state: Arc::new(state),
state,
presence: None,
prefixes: Arc::new(prefixes),
intents: Intents::empty(),
extras: Arc::new(extras),
cached_resource_types: Vec::new(),
commands: Vec::new(),
components: Vec::new(),
tasks: Vec::new(),
on_ready_handlers: Vec::new(),
on_reconnect_handlers: Vec::new(),
on_interaction_handlers: vec![Arc::new(InteractionRunner)],
@@ -124,6 +147,7 @@ impl<T: 'static + Send + Sync> Bot<T> {
on_server_create_handlers: Vec::new(),
on_server_update_handlers: Vec::new(),
on_server_delete_handlers: Vec::new(),
topgg_token: None,
}
}
@@ -137,64 +161,91 @@ impl<T: 'static + Send + Sync> Bot<T> {
self
}
pub fn command(mut self, command: impl Command<T> + 'static) -> Self {
pub fn presence(mut self, presence: UpdatePresencePayload) -> Self {
self.presence = Some(presence);
self
}
pub fn command(mut self, command: impl Command<T, E> + 'static) -> Self {
self.commands.push(Arc::new(command));
self
}
pub fn component(mut self, component: impl Component<T> + 'static) -> Self {
pub fn component(mut self, component: impl Component<T, E> + 'static) -> Self {
self.components.push(Arc::new(component));
self
}
pub fn on_ready(mut self, handler: impl OnReadyHandler<T> + 'static) -> Self {
#[allow(dead_code)]
pub fn task(mut self, task: impl Task<T, E> + 'static) -> Self {
self.tasks.push(Arc::new(task));
self
}
pub fn cache_resource_type(mut self, resource_type: ResourceType) -> Self {
if !self.cached_resource_types.contains(&resource_type) {
self.cached_resource_types.push(resource_type);
}
self
}
pub fn on_ready(mut self, handler: impl OnReadyHandler<T, E> + 'static) -> Self {
self.on_ready_handlers.push(Arc::new(handler));
self
}
pub fn on_reconnect(mut self, handler: impl OnReconnectHandler<T> + 'static) -> Self {
pub fn on_reconnect(mut self, handler: impl OnReconnectHandler<T, E> + 'static) -> Self {
self.on_reconnect_handlers.push(Arc::new(handler));
self
}
#[allow(dead_code)]
pub fn on_interaction(mut self, handler: impl OnInteractionHandler<T> + 'static) -> Self {
pub fn on_interaction(mut self, handler: impl OnInteractionHandler<T, E> + 'static) -> Self {
self.on_interaction_handlers.push(Arc::new(handler));
self
}
pub fn on_message(mut self, handler: impl OnMessageHandler<T> + 'static) -> Self {
pub fn on_message(mut self, handler: impl OnMessageHandler<T, E> + 'static) -> Self {
self.on_message_handlers.push(Arc::new(handler));
self
}
#[allow(dead_code)]
pub fn on_message_edit(mut self, handler: impl OnMessageEditHandler<T> + 'static) -> Self {
pub fn on_message_edit(mut self, handler: impl OnMessageEditHandler<T, E> + 'static) -> Self {
self.on_message_edit_handlers.push(Arc::new(handler));
self
}
#[allow(dead_code)]
pub fn on_message_delete(mut self, handler: impl OnMessageDeleteHandler<T> + 'static) -> Self {
pub fn on_message_delete(
mut self,
handler: impl OnMessageDeleteHandler<T, E> + 'static,
) -> Self {
self.on_message_delete_handlers.push(Arc::new(handler));
self
}
pub fn on_server_create(mut self, handler: impl OnServerCreateHandler<T> + 'static) -> Self {
pub fn on_server_create(mut self, handler: impl OnServerCreateHandler<T, E> + 'static) -> Self {
self.on_server_create_handlers.push(Arc::new(handler));
self
}
pub fn on_server_update(mut self, handler: impl OnServerUpdateHandler<T> + 'static) -> Self {
pub fn on_server_update(mut self, handler: impl OnServerUpdateHandler<T, E> + 'static) -> Self {
self.on_server_update_handlers.push(Arc::new(handler));
self
}
pub fn on_server_delete(mut self, handler: impl OnServerDeleteHandler<T> + 'static) -> Self {
pub fn on_server_delete(mut self, handler: impl OnServerDeleteHandler<T, E> + 'static) -> Self {
self.on_server_delete_handlers.push(Arc::new(handler));
self
}
pub fn topgg_token(mut self, token: impl ToString) -> Self {
self.topgg_token = Some(token.to_string());
self
}
pub async fn run(self, token: &str) -> Result<(), RuntimeError> {
let http = Client::new(token.to_string());
let app = http
@@ -206,6 +257,60 @@ impl<T: 'static + Send + Sync> Bot<T> {
.await
.inspect_err(|e| log::error!("Could not parse application data! {e:?}"))
.map_err(|_| RuntimeError::ApplicationFetchingFailed)?;
if let Some(topgg_token) = &self.topgg_token
&& self.shard.number() == 0
{
let topgg_token = topgg_token.clone();
let http = Client::new(token.to_string());
tokio::spawn(async move {
let topgg_client = topgg::Client::new(topgg_token);
loop {
let app = match http
.current_user_application()
.await
.map_err(|_| RuntimeError::ApplicationFetchingFailed)
{
Ok(v) => {
match v
.model()
.await
.map_err(|_| RuntimeError::ApplicationFetchingFailed)
{
Ok(app) => app,
Err(err) => {
log::warn!(
"Could not parse application data, skipping stats post to Top.gg! {err:?}"
);
continue;
}
}
}
Err(err) => {
log::warn!(
"Could not fetch application data, skipping stats post to Top.gg! {err:?}"
);
continue;
}
};
topgg_client
.post_stats(Stats::from_count(
app.approximate_guild_count.unwrap() as usize,
Some(self.shard.total() as usize),
))
.await
.inspect_err(|err| {
log::warn!("Could not report bot stats to Top.gg: {err}")
})
.ok();
tokio::time::sleep(Duration::from_secs(120)).await;
}
});
}
let registry = ComponentRegistry::new();
for component in &self.components {
@@ -219,6 +324,18 @@ impl<T: 'static + Send + Sync> Bot<T> {
let bot = Arc::new(self);
let mut resource_types = ResourceType::empty();
for resource_type in &bot.cached_resource_types {
resource_types.insert(*resource_type);
}
let cache = DefaultInMemoryCache::builder()
.resource_types(resource_types)
.build();
let (gateway_tx, mut gateway_rx) = tokio::sync::mpsc::unbounded_channel();
let runtime = Arc::new(Runtime {
http,
app,
@@ -226,123 +343,159 @@ impl<T: 'static + Send + Sync> Bot<T> {
state: bot.state.clone(),
prefixes: bot.prefixes.clone(),
commands: bot.commands.clone(),
cache,
gateway_tx,
shard_number: bot.shard.number(),
shard_total: bot.shard.total(),
});
let mut gateway = Shard::new(bot.shard, token.to_string(), bot.intents);
for task in bot.tasks.clone() {
let task_rt = runtime.clone();
tokio::spawn(async move {
loop {
task.run(&task_rt)
.await
.inspect_err(|e| {
log::error!("An error occurred while running task {task:?}! {e:?}")
})
.bye();
tokio::time::sleep(task.delay()).await;
}
});
}
let mut config = ConfigBuilder::new(token.to_string(), bot.intents);
if let Some(presence) = &bot.presence {
config = config.presence(presence.clone());
}
let config = config.build();
let mut gateway = Shard::with_config(bot.shard, config);
loop {
if let Some(Ok(event)) = gateway.next_event(EventTypeFlags::all()).await {
let task_rt = runtime.clone();
let task_bot = bot.clone();
tokio::select! {
Some(Ok(event)) = gateway.next_event(EventTypeFlags::all()) => {
let task_rt = runtime.clone();
let task_bot = bot.clone();
tokio::spawn(async move {
match event {
Event::Ready(event) => {
for handler in &task_bot.on_ready_handlers {
handler
.on_ready(&event, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on ready for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GatewayReconnect => {
for handler in &task_bot.on_reconnect_handlers {
handler
.on_reconnect(task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on reconnect for {handler:?}! {e:?}")
)
.bye();
}
}
Event::InteractionCreate(interaction) => {
for handler in &task_bot.on_interaction_handlers {
handler
.on_interaction(&interaction, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on interaction for {handler:?}! {e:?}")
)
.bye();
}
}
Event::MessageCreate(message) => {
for handler in &task_bot.on_message_handlers {
log::trace!("Running {handler:?}");
tokio::spawn(async move {
task_rt.cache.update(&event);
handler
.on_message(&message, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on message for {handler:?}! {e:?}")
)
.bye();
match event {
Event::Ready(event) => {
for handler in &task_bot.on_ready_handlers {
handler
.on_ready(&event, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on ready for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GatewayReconnect => {
for handler in &task_bot.on_reconnect_handlers {
handler
.on_reconnect(task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on reconnect for {handler:?}! {e:?}")
)
.bye();
}
}
Event::InteractionCreate(interaction) => {
for handler in &task_bot.on_interaction_handlers {
handler
.on_interaction(&interaction, task_rt.clone(), task_bot.extras.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on interaction for {handler:?}! {e:?}")
)
.bye();
}
}
Event::MessageCreate(message) => {
for handler in &task_bot.on_message_handlers {
log::trace!("Running {handler:?}");
handler
.on_message(&message, task_rt.clone(), task_bot.extras.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on message for {handler:?}! {e:?}")
)
.bye();
}
}
Event::MessageUpdate(message) => {
for handler in &task_bot.on_message_edit_handlers {
handler
.on_message_edit(&message, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on message edit for {handler:?}! {e:?}")
)
.bye();
}
}
Event::MessageDelete(message) => {
for handler in &task_bot.on_message_delete_handlers {
handler
.on_message_delete(&message, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on message delete for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GuildCreate(guild) => {
for handler in &task_bot.on_server_create_handlers {
handler
.on_server_create(&guild, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on server create for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GuildUpdate(guild) => {
for handler in &task_bot.on_server_update_handlers {
handler
.on_server_update(&guild, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on server update for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GuildDelete(guild) => {
for handler in &task_bot.on_server_delete_handlers {
handler
.on_server_delete(&guild, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on server delete for {handler:?}! {e:?}")
)
.bye();
}
}
_ => {
log::trace!("Unhandled event {:?} received", event.kind());
}
}
Event::MessageUpdate(message) => {
for handler in &task_bot.on_message_edit_handlers {
handler
.on_message_edit(&message, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on message edit for {handler:?}! {e:?}")
)
.bye();
}
}
Event::MessageDelete(message) => {
for handler in &task_bot.on_message_delete_handlers {
handler
.on_message_delete(&message, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on message delete for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GuildCreate(guild) => {
for handler in &task_bot.on_server_create_handlers {
handler
.on_server_create(&guild, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on server create for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GuildUpdate(guild) => {
for handler in &task_bot.on_server_update_handlers {
handler
.on_server_update(&guild, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on server update for {handler:?}! {e:?}")
)
.bye();
}
}
Event::GuildDelete(guild) => {
for handler in &task_bot.on_server_delete_handlers {
handler
.on_server_delete(&guild, task_rt.clone())
.await
.inspect_err(
|e| log::error!("An error occurred while handling on server delete for {handler:?}! {e:?}")
)
.bye();
}
}
_ => {
log::trace!("Unhandled event {:?} received", event.kind());
}
}
});
});
}
Some(json) = gateway_rx.recv() => {
gateway.command(&json);
}
}
}
}
-3
View File
@@ -1,3 +0,0 @@
pub struct RedisCache {
}
+103 -56
View File
@@ -1,10 +1,11 @@
use std::{
fmt,
ops::{Deref, DerefMut},
};
use std::fmt;
use std::ops::{Deref, DerefMut};
use thiserror::Error;
use crate::database::models::DatabaseError;
use crate::framework::commands::context::CommandContext;
#[derive(Debug, Error)]
pub enum ArgumentParsingError {
#[error("This argument was missing in the arguments array")]
@@ -12,14 +13,23 @@ pub enum ArgumentParsingError {
#[error("An argument was there but it could not be parsed into the specified value")]
InvalidArgument,
#[error("A database operation failed")]
DatabaseFailed(#[from] DatabaseError),
}
pub trait FromArguments: Sized {
fn from_args(args: &str) -> Result<(Self, &str), ArgumentParsingError>;
pub trait FromArguments<S, E>: Sized {
async fn from_args<'a>(
args: &'a str,
ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError>;
}
impl FromArguments for String {
fn from_args(args: &str) -> Result<(Self, &str), ArgumentParsingError> {
impl<S, E> FromArguments<S, E> for String {
async fn from_args<'a>(
args: &'a str,
_ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
if !args.is_empty() {
match args.split_once(" ") {
Some((arg, rest)) => Ok((arg.to_string(), rest)),
@@ -37,8 +47,11 @@ impl FromArguments for String {
/// Parsing this argument type never fails.
pub struct GreedyString(pub String);
impl FromArguments for GreedyString {
fn from_args<'a>(args: &str) -> Result<(Self, &str), ArgumentParsingError> {
impl<S, E> FromArguments<S, E> for GreedyString {
async fn from_args<'a>(
args: &'a str,
_ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
let value = GreedyString(args.to_string());
Ok((value, ""))
@@ -87,9 +100,12 @@ impl fmt::Display for NeedyString {
}
}
impl FromArguments for NeedyString {
fn from_args(args: &str) -> Result<(Self, &str), ArgumentParsingError> {
if !args.is_empty() {
impl<S, E> FromArguments<S, E> for NeedyString {
async fn from_args<'a>(
args: &'a str,
_ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
if !args.trim().is_empty() {
match args.split_once(" ") {
Some((arg, rest)) => Ok((Self(arg.to_string()), rest)),
None => Ok((Self(args.to_string()), "")),
@@ -122,18 +138,24 @@ impl fmt::Display for NeedyGreedyString {
}
}
impl FromArguments for NeedyGreedyString {
fn from_args(args: &str) -> Result<(Self, &str), ArgumentParsingError> {
if !args.is_empty() {
Ok((Self(args.to_string()), ""))
impl<S, E> FromArguments<S, E> for NeedyGreedyString {
async fn from_args<'a>(
args: &'a str,
_ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
if !args.trim().is_empty() {
Ok((Self(args.trim().to_string()), ""))
} else {
Err(ArgumentParsingError::MissingArgument)
}
}
}
impl FromArguments for bool {
fn from_args(args: &str) -> Result<(Self, &str), ArgumentParsingError> {
impl<S, E> FromArguments<S, E> for bool {
async fn from_args<'a>(
args: &'a str,
_ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
let arg: &str;
let rest: &str;
@@ -148,7 +170,7 @@ impl FromArguments for bool {
}
}
match arg {
match arg.to_lowercase().as_str() {
"y" | "yes" | "on" | "true" | "t" | "1" => Ok((true, rest)),
"n" | "no" | "off" | "false" | "f" | "0" => Ok((false, rest)),
_ => Err(ArgumentParsingError::InvalidArgument),
@@ -156,73 +178,98 @@ impl FromArguments for bool {
}
}
impl<T> FromArguments for Option<T>
impl<T, S, E> FromArguments<S, E> for Option<T>
where
T: FromArguments,
T: FromArguments<S, E>,
{
fn from_args(args: &str) -> Result<(Self, &str), ArgumentParsingError> {
match T::from_args(args) {
async fn from_args<'a>(
args: &'a str,
_ctx: &'a CommandContext<'_, S, E>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
match T::from_args(args, _ctx).await {
Ok((result, rest)) => Ok((Some(result), rest)),
Err(_) => Ok((None, args)),
}
}
}
pub trait ParseArguments: Sized {
fn parse(args: &str) -> Result<Self, ArgumentParsingError>;
}
pub struct Arg<T>(pub T);
impl ParseArguments for () {
fn parse(_: &str) -> Result<Self, ArgumentParsingError> {
Ok(())
impl<T> Deref for Arg<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<A> ParseArguments for A
where
A: FromArguments,
{
fn parse(args: &str) -> Result<Self, ArgumentParsingError> {
let (a, _) = A::from_args(args)?;
Ok(a)
impl<T> DerefMut for Arg<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<A> ParseArguments for (A,)
pub trait ParseArguments<S, E>: Sized {
async fn parse(args: &str, ctx: &CommandContext<S, E>) -> Result<Self, ArgumentParsingError>;
}
impl<T, S, E> ParseArguments<S, E> for Arg<T>
where
A: FromArguments,
T: FromArguments<S, E>,
{
fn parse(args: &str) -> Result<Self, ArgumentParsingError> {
let (a, _) = A::from_args(args)?;
async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (value, _) = T::from_args(args, ctx).await?;
Ok(Arg(value))
}
}
impl<A, S, E> ParseArguments<S, E> for (A,)
where
A: FromArguments<S, E>,
{
async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (a, _) = A::from_args(args, ctx).await?;
Ok((a,))
}
}
impl<A, B> ParseArguments for (A, B)
impl<A, B, S, E> ParseArguments<S, E> for (A, B)
where
A: FromArguments,
B: FromArguments,
A: FromArguments<S, E>,
B: FromArguments<S, E>,
{
fn parse(args: &str) -> Result<Self, ArgumentParsingError> {
let (a, args) = A::from_args(args)?;
let (b, _) = B::from_args(args)?;
async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (a, args) = A::from_args(args, ctx).await?;
let (b, _) = B::from_args(args, ctx).await?;
Ok((a, b))
}
}
impl<A, B, C> ParseArguments for (A, B, C)
impl<A, B, C, S, E> ParseArguments<S, E> for (A, B, C)
where
A: FromArguments,
B: FromArguments,
C: FromArguments,
A: FromArguments<S, E>,
B: FromArguments<S, E>,
C: FromArguments<S, E>,
{
fn parse(args: &str) -> Result<Self, ArgumentParsingError> {
let (a, args) = A::from_args(args)?;
let (b, args) = B::from_args(args)?;
let (c, _) = C::from_args(args)?;
async fn parse(
args: &str,
ctx: &CommandContext<'_, S, E>,
) -> Result<Self, ArgumentParsingError> {
let (a, args) = A::from_args(args, ctx).await?;
let (b, args) = B::from_args(args, ctx).await?;
let (c, _) = C::from_args(args, ctx).await?;
Ok((a, b, c))
}
+80 -7
View File
@@ -1,24 +1,97 @@
use std::sync::Arc;
use twilight_http::{Error, Response};
use twilight_model::channel::Message;
use twilight_model::channel::message::Component;
use twilight_model::gateway::payload::incoming::MessageCreate;
use crate::framework::{commands::messages::MessageSender, runtime::Runtime};
use crate::framework::commands::messages::MessageSender;
use crate::framework::interactions::components::ActionRow;
use crate::framework::messages::MessageBuilder;
use crate::framework::runtime::Runtime;
pub struct CommandContext<'a, T> {
pub struct CommandContext<'a, T, E> {
pub event: &'a MessageCreate,
pub rt: Arc<Runtime<T>>,
pub rt: Arc<Runtime<T, E>>,
pub prefix: &'a str,
pub extras: E,
}
impl<'a, T> CommandContext<'a, T>
impl<'a, T, E> CommandContext<'a, T, E>
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
pub fn new(event: &'a MessageCreate, rt: Arc<Runtime<T>>, prefix: &'a str) -> Self {
Self { event, rt, prefix }
pub fn new(
event: &'a MessageCreate,
rt: Arc<Runtime<T, E>>,
prefix: &'a str,
extras: E,
) -> Self {
Self {
event,
rt,
prefix,
extras,
}
}
pub fn send(&self) -> MessageSender<T> {
pub fn send(&self) -> MessageSender<T, E> {
MessageSender::new(self.event.channel_id, self.rt.clone())
}
pub async fn send_from_builder(
&self,
builder: MessageBuilder<T, E>,
) -> Result<Response<Message>, Error> {
let mut sender = self.rt.http.create_message(self.event.channel_id);
if let Some(content) = &builder.content {
sender = sender.content(content);
}
let mut current_row = ActionRow::new(&[]);
let mut current_index = 0;
let mut rows: Vec<Component> = vec![];
let mut custom_ids: Vec<String> = vec![];
for (component, index) in builder.components {
if index != current_index {
if !current_row.is_empty() {
rows.push(current_row.build());
current_row = ActionRow::new(&[]);
}
current_index += 1;
}
let custom_id = component.custom_id();
if let Some(custom_id) = &custom_id {
custom_ids.push(custom_id.clone());
self.rt.registry.register(custom_id, component.clone());
}
current_row.add(custom_id.clone(), component.clone());
}
if !current_row.is_empty() {
rows.push(current_row.build());
}
sender = sender.components(&rows);
sender = sender.embeds(&builder.embeds);
let result = sender.await;
if result.is_err() {
for custom_id in custom_ids {
self.rt.registry.unregister(custom_id);
}
}
result
}
}
+32
View File
@@ -0,0 +1,32 @@
use std::error::Error;
use async_trait::async_trait;
use twilight_model::user::User;
use crate::framework::runtime::Runtime;
#[async_trait]
pub trait ExtrasGetter<S>: Send + Sync {
type Extras;
async fn get_extra(
&self,
user: &User,
rt: &Runtime<S, Self::Extras>,
) -> Result<Self::Extras, Box<dyn Error>>;
}
pub struct DefaultExtraGetter;
#[async_trait]
impl<S> ExtrasGetter<S> for DefaultExtraGetter {
type Extras = ();
async fn get_extra(
&self,
_user: &User,
_rt: &Runtime<S, Self::Extras>,
) -> Result<Self::Extras, Box<dyn Error>> {
Ok(())
}
}
+42 -35
View File
@@ -1,50 +1,44 @@
use std::{
future::{Future, IntoFuture},
pin::Pin,
sync::Arc,
};
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::sync::Arc;
use twilight_http::{Error, Response, response::marker::EmptyBody};
use twilight_model::{
channel::{
Message,
message::{Component as TwilightComponent, Embed},
},
http::interaction::{InteractionResponse, InteractionResponseType},
id::{
Id,
marker::{ChannelMarker, InteractionMarker},
},
};
use twilight_http::response::marker::EmptyBody;
use twilight_http::{Error, Response};
use twilight_model::channel::Message;
use twilight_model::channel::message::{Component as TwilightComponent, Embed};
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_model::id::Id;
use twilight_model::id::marker::{ChannelMarker, InteractionMarker, MessageMarker};
use twilight_util::builder::InteractionResponseDataBuilder;
use crate::framework::{
interactions::components::{ActionRow, Component},
runtime::Runtime,
};
use crate::framework::interactions::components::{ActionRow, Component};
use crate::framework::runtime::Runtime;
pub struct MessageSender<T> {
pub struct MessageSender<T, E> {
channel_id: Id<ChannelMarker>,
rt: Arc<Runtime<T>>,
rt: Arc<Runtime<T, E>>,
content: Option<String>,
embeds: Vec<Embed>,
reply_to: Option<Id<MessageMarker>>,
// Row index, component
components: Vec<(u8, Arc<dyn Component<T>>)>,
components: Vec<(u8, Arc<dyn Component<T, E>>)>,
}
impl<T> MessageSender<T>
impl<T, E> MessageSender<T, E>
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
pub fn new(channel_id: Id<ChannelMarker>, rt: Arc<Runtime<T>>) -> Self {
pub fn new(channel_id: Id<ChannelMarker>, rt: Arc<Runtime<T, E>>) -> Self {
Self {
channel_id,
rt,
content: None,
components: vec![],
reply_to: None,
embeds: vec![],
}
}
@@ -61,12 +55,18 @@ where
self
}
pub fn component(mut self, component: impl Component<T> + 'static, row: u8) -> Self {
pub fn component(mut self, component: impl Component<T, E> + 'static, row: u8) -> Self {
self.components.push((row, Arc::new(component)));
self
}
pub fn reply_to(mut self, message_id: Id<MessageMarker>) -> Self {
self.reply_to = Some(message_id);
self
}
pub async fn send(self) -> Result<Response<Message>, Error> {
let mut builder = self.rt.http.create_message(self.channel_id);
@@ -108,6 +108,10 @@ where
builder = builder.components(&rows);
builder = builder.embeds(&self.embeds);
if let Some(reply_to) = self.reply_to {
builder = builder.reply(reply_to);
}
let result = builder.await;
if result.is_err() {
@@ -120,7 +124,7 @@ where
}
}
impl<T: Send + Sync + 'static> IntoFuture for MessageSender<T> {
impl<T: Send + Sync + 'static, E: Send + Sync + 'static> IntoFuture for MessageSender<T, E> {
type Output = Result<Response<Message>, Error>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
@@ -129,27 +133,28 @@ impl<T: Send + Sync + 'static> IntoFuture for MessageSender<T> {
}
}
pub struct OriginalMessageUpdater<T> {
pub struct OriginalMessageUpdater<T, E> {
interaction_id: Id<InteractionMarker>,
interaction_token: String,
rt: Arc<Runtime<T>>,
rt: Arc<Runtime<T, E>>,
content: Option<String>,
embeds: Vec<Embed>,
// Row index, component
components: Vec<(u8, Arc<dyn Component<T>>)>,
components: Vec<(u8, Arc<dyn Component<T, E>>)>,
}
impl<T> OriginalMessageUpdater<T>
impl<T, E> OriginalMessageUpdater<T, E>
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
pub fn new(
interaction_id: Id<InteractionMarker>,
interaction_token: String,
rt: Arc<Runtime<T>>,
rt: Arc<Runtime<T, E>>,
) -> Self {
Self {
interaction_id,
@@ -174,7 +179,7 @@ where
self
}
pub fn component(mut self, component: impl Component<T> + 'static, row: u8) -> Self {
pub fn component(mut self, component: impl Component<T, E> + 'static, row: u8) -> Self {
self.components.push((row, Arc::new(component)));
self
@@ -245,7 +250,9 @@ where
}
}
impl<T: Send + Sync + 'static> IntoFuture for OriginalMessageUpdater<T> {
impl<T: Send + Sync + 'static, E: Send + Sync + 'static> IntoFuture
for OriginalMessageUpdater<T, E>
{
type Output = Result<Response<EmptyBody>, Error>;
type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send>>;
+148 -23
View File
@@ -1,26 +1,29 @@
use std::fmt::Debug;
use async_trait::async_trait;
use deadpool_redis::cluster::PoolError;
use deadpool_redis::redis::RedisError;
use thiserror::Error;
use twilight_http::response::DeserializeBodyError;
use crate::framework::commands::{
arguments::Argument, context::CommandContext, permissions::Permission,
};
use crate::database::models::{DatabaseError, DatabaseOrDiscordError};
use crate::framework::commands::arguments::Argument;
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::framework::runtime::Runtime;
pub mod arguments;
pub mod context;
pub mod extras;
pub mod messages;
pub mod permissions;
pub mod runner;
/// An error occurred during command execution.
#[derive(Debug, Error)]
pub enum CommandError {
#[error("A message was attempted to be sent but it failed")]
MessageSendingFailed,
#[error("A database query failed")]
DatabaseQueryFailed,
DatabaseFailed(#[from] DatabaseError),
#[error("A database operation failed due to an inconsistent state")]
DatabaseInconsistentState,
@@ -33,24 +36,95 @@ pub enum CommandError {
#[error(transparent)]
DiscordDeserializationFailed(#[from] DeserializeBodyError),
#[error(transparent)]
RedisPoolFailed(#[from] PoolError),
#[error(transparent)]
RedisFailed(#[from] RedisError),
#[error(transparent)]
DatabaseOrDiscordError(#[from] DatabaseOrDiscordError),
}
/// Represents a bot command.
///
/// Only the [`Command::name()`] and the [`Command::execute()`] methods must be implemented. The
/// rest have default implementations. They can all be overriden to tweak the command's behavior
/// and display in the help command.
#[async_trait]
pub trait Command<T>: Send + Sync + Debug {
pub trait Command<T, E>: Send + Sync + Debug {
/// The command's name.
///
/// Returns:
/// [`&'static str`] - The command's name.
fn name(&self) -> &'static str;
/// The command's aliases.
///
/// Returns:
/// [`&'static [&'static str]`] - The command's aliases.
fn aliases(&self) -> &'static [&'static str] {
&[]
}
/// The command's description, shown in the help command.
///
/// Returns:
/// [`&'static str`] - The command's description.
fn description(&self) -> &'static str {
"A Payphone command."
}
/// The command's arguments, shown in the help command.
///
/// This does not affect parsing in any way, as that's done inside [`Command::execute()`]. This
/// is for display in the help command only.
///
/// Returns:
/// [`&'static [Argument]`] - The command's arguments.
fn arguments(&self) -> &'static [Argument] {
&[]
}
fn permissions(&self) -> Vec<Box<dyn Permission<T> + Send + Sync + 'static>> {
/// Permissions that will be checked for before running the command.
///
/// If any of the permissions fail, the command will not be run and the permission's
/// [`Permission::on_handle_denied()`] will be called.
///
/// Returns:
/// [`Vec<Box<dyn Permission<T, E> + Send + Sync>>`] - A vector of the command's permissions.
fn permissions(&self) -> Vec<Box<dyn Permission<T, E> + Send + Sync + 'static>> {
vec![]
}
/// Whether the command should be shown in the help command.
///
/// This is useful for commands that are not meant to be used by users directly, like internal
/// commands or easter egg commands.
///
/// Returns:
/// [`bool`] - Whether the command should be shown in the help command.
fn show_in_help(&self, _rt: &Runtime<T, E>, _extras: &E) -> bool {
true
}
/// Whether the command only runs when the message starts with the command prefix.
///
/// When this is false, the command will be run when the command is found on any part of the
/// message. This is useful for about-group commands, like:
///
/// ```text
/// User: You can donate $6 at p.d to get unbanned.
/// Bot: https://ko-fi.com/payphonedev
/// ```
///
/// Returns:
/// [`bool`] - Whether the command only runs when the message starts with the command prefix.
fn only_runs_if_startswith(&self) -> bool {
true
}
/// Returns the command name + all its aliases.
///
/// Returns:
@@ -61,35 +135,86 @@ pub trait Command<T>: Send + Sync + Debug {
all
}
async fn execute(&self, ctx: CommandContext<'_, T>, args: &str) -> Result<(), CommandError>;
/// Executes the command.
///
/// Arguments:
/// * `ctx` - The command context, containing information about the command invocation and
/// helpers for responding.
/// * `args` - The raw arguments passed to the command, without any parsing. This is the part
/// of the message after the command name.
///
/// Returns:
/// [`Result<(), CommandError>`] - Ok if the command executed successfully, or an error if
/// something went wrong during execution.
async fn execute(&self, ctx: CommandContext<'_, T, E>, args: &str) -> Result<(), CommandError>;
}
/// The parts of a command found in a message, without processing.
///
/// This is not guaranteed to point to a valid command, as it only finds a prefix in a message and
/// parses it without checking for command existance nor argument validity.
pub struct CommandParts<'a> {
/// The name of the command.
pub name: &'a str,
/// The arguments passed to the command, raw as a string.
pub args: &'a str,
/// The index in the start-trimmed message where the command was found.
///
/// For example, given the prefix is `p.`:
/// ```text
/// Donate $6 at p.d to get unbanned.
/// ^
/// index = 13
/// ```
pub start_index: usize,
}
impl<'a> CommandParts<'a> {
fn new(name: &'a str, args: &'a str) -> Self {
Self { name, args }
/// Creates a new [`CommandParts`] struct.
///
/// Arguments:
/// * `name` - The name of the command.
/// * `args` - The arguments passed to the command, raw as a string.
/// * `start_index` - The index in the start-trimmed message where the command was found.
///
/// Returns:
/// [`CommandParts`] - The created struct.
fn new(name: &'a str, args: &'a str, start_index: usize) -> Self {
Self {
name,
args,
start_index,
}
}
}
/// Parses a message content to get the command name and arguments.
///
/// Arguments:
/// * `prefix` - The prefix to look for in the message.
/// * `message` - The message content to parse.
///
/// Returns:
/// [`Option<CommandParts>`] - The parsed command parts, or None if the prefix was not found in the
/// message.
pub fn get_command_parts<'a>(prefix: &str, message: &'a str) -> Option<CommandParts<'a>> {
let message_trimmed_start = message.trim_ascii_start();
let message_trimmed_start_lowercase = message_trimmed_start.to_ascii_lowercase();
if message_trimmed_start
.to_ascii_lowercase()
.starts_with(&prefix.to_ascii_lowercase())
{
let message = message_trimmed_start
.split_at(prefix.len())
.1
.trim_ascii_start();
let prefix_lowercase = prefix.to_ascii_lowercase();
match message.split_once(" ") {
Some((name, args)) => Some(CommandParts::new(name, args)),
None => Some(CommandParts::new(message, "")),
if let Some(index) = message_trimmed_start_lowercase.find(&prefix_lowercase) {
let command_text = &message_trimmed_start[index + prefix.len()..];
match command_text.trim_ascii_start().split_once(" ") {
Some((name, args)) => Some(CommandParts::new(name, args, index)),
None => Some(CommandParts::new(
command_text.trim_ascii_start(),
"",
index,
)),
}
} else {
None
+8 -3
View File
@@ -2,9 +2,14 @@ use std::fmt::Debug;
use async_trait::async_trait;
use crate::framework::commands::{CommandError, context::CommandContext};
use crate::framework::commands::CommandError;
use crate::framework::commands::context::CommandContext;
#[async_trait]
pub trait Permission<S: Send + Sync + 'static>: Debug {
async fn check(&self, ctx: &CommandContext<S>) -> Result<bool, CommandError>;
pub trait Permission<S: Send + Sync + 'static, E>: Debug {
async fn check(&self, ctx: &CommandContext<S, E>) -> Result<bool, CommandError>;
async fn on_handle_denied(&self, _ctx: &CommandContext<S, E>) -> Result<(), CommandError> {
Ok(())
}
}
+27 -8
View File
@@ -3,18 +3,27 @@ use std::sync::Arc;
use async_trait::async_trait;
use twilight_model::gateway::payload::incoming::MessageCreate;
use crate::framework::{
commands::{context::CommandContext, get_command_parts},
events::traits::{EventResult, OnMessageHandler},
runtime::Runtime,
};
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::commands::get_command_parts;
use crate::framework::events::traits::{EventResult, OnMessageHandler};
use crate::framework::runtime::Runtime;
#[derive(Debug)]
pub struct CommandRunner;
#[async_trait]
impl<T: Send + Sync + 'static> OnMessageHandler<T> for CommandRunner {
async fn on_message(&self, event: &MessageCreate, rt: Arc<Runtime<T>>) -> EventResult {
impl<T, E> OnMessageHandler<T, E> for CommandRunner
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
async fn on_message(
&self,
event: &MessageCreate,
rt: Arc<Runtime<T, E>>,
extras: Arc<dyn ExtrasGetter<T, Extras = E>>,
) -> EventResult {
if event.author.bot || event.author.system.unwrap_or(false) {
return Ok(());
}
@@ -31,7 +40,16 @@ impl<T: Send + Sync + 'static> OnMessageHandler<T> for CommandRunner {
});
if let Some(command) = command {
let ctx = CommandContext::new(event, rt.clone(), &prefixes[0]);
if command.only_runs_if_startswith() && parts.start_index != 0 {
continue;
}
let extras = extras
.get_extra(&event.author, &rt)
.await
.inspect_err(|e| log::error!("Failed to get extras: {e}"))?;
let ctx = CommandContext::new(event, rt.clone(), &prefixes[0], extras);
for permission in command.permissions() {
if !permission
@@ -39,6 +57,7 @@ impl<T: Send + Sync + 'static> OnMessageHandler<T> for CommandRunner {
.await
.inspect_err(|e| log::error!("Permission check failed: {e}"))?
{
permission.on_handle_denied(&ctx).await?;
return Ok(());
}
}
+42 -19
View File
@@ -1,4 +1,6 @@
use std::{error::Error, fmt::Debug, sync::Arc};
use std::error::Error;
use std::fmt::Debug;
use std::sync::Arc;
use async_trait::async_trait;
use twilight_model::gateway::payload::incoming::{
@@ -6,78 +8,99 @@ use twilight_model::gateway::payload::incoming::{
MessageUpdate, Ready,
};
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::runtime::Runtime;
pub type EventResult = Result<(), Box<dyn Error>>;
#[async_trait]
pub trait OnReadyHandler<T>: Send + Sync + Debug
pub trait OnReadyHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_ready(&self, event: &Ready, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_ready(&self, event: &Ready, rt: Arc<Runtime<T, E>>) -> EventResult;
}
#[async_trait]
pub trait OnReconnectHandler<T>: Send + Sync + Debug
pub trait OnReconnectHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_reconnect(&self, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_reconnect(&self, rt: Arc<Runtime<T, E>>) -> EventResult;
}
#[async_trait]
pub trait OnInteractionHandler<T>: Send + Sync + Debug
pub trait OnInteractionHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_interaction(&self, event: &InteractionCreate, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_interaction(
&self,
event: &InteractionCreate,
rt: Arc<Runtime<T, E>>,
extras: Arc<dyn ExtrasGetter<T, Extras = E>>,
) -> EventResult;
}
#[async_trait]
pub trait OnMessageHandler<T>: Send + Sync + Debug
pub trait OnMessageHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_message(&self, event: &MessageCreate, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_message(
&self,
event: &MessageCreate,
rt: Arc<Runtime<T, E>>,
extras: Arc<dyn ExtrasGetter<T, Extras = E>>,
) -> EventResult;
}
#[async_trait]
pub trait OnMessageEditHandler<T>: Send + Sync + Debug
pub trait OnMessageEditHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_message_edit(&self, event: &MessageUpdate, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_message_edit(&self, event: &MessageUpdate, rt: Arc<Runtime<T, E>>) -> EventResult;
}
#[async_trait]
pub trait OnMessageDeleteHandler<T>: Send + Sync + Debug
pub trait OnMessageDeleteHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_message_delete(&self, event: &MessageDelete, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_message_delete(&self, event: &MessageDelete, rt: Arc<Runtime<T, E>>)
-> EventResult;
}
#[async_trait]
pub trait OnServerCreateHandler<T>: Send + Sync + Debug
pub trait OnServerCreateHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_server_create(&self, event: &GuildCreate, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_server_create(&self, event: &GuildCreate, rt: Arc<Runtime<T, E>>) -> EventResult;
}
#[async_trait]
pub trait OnServerUpdateHandler<T>: Send + Sync + Debug
pub trait OnServerUpdateHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_server_update(&self, event: &GuildUpdate, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_server_update(&self, event: &GuildUpdate, rt: Arc<Runtime<T, E>>) -> EventResult;
}
#[async_trait]
pub trait OnServerDeleteHandler<T>: Send + Sync + Debug
pub trait OnServerDeleteHandler<T, E>: Send + Sync + Debug
where
T: Send + Sync,
E: Send + Sync,
{
async fn on_server_delete(&self, event: &GuildDelete, rt: Arc<Runtime<T>>) -> EventResult;
async fn on_server_delete(&self, event: &GuildDelete, rt: Arc<Runtime<T, E>>) -> EventResult;
}
+38 -23
View File
@@ -1,27 +1,29 @@
use std::{fmt::Debug, sync::Arc};
use std::fmt::Debug;
use std::sync::Arc;
use async_trait::async_trait;
use twilight_model::channel::message::{
Component as TwilightComponent,
component::{ActionRow as TwilightActionRow, Button as TwilightButton, ButtonStyle},
use twilight_model::channel::message::Component as TwilightComponent;
use twilight_model::channel::message::component::{
ActionRow as TwilightActionRow, Button as TwilightButton, ButtonStyle,
};
use crate::framework::interactions::{InteractionError, context::InteractionContext};
use crate::framework::interactions::InteractionError;
use crate::framework::interactions::context::InteractionContext;
type ComponentWithID<T> = (Option<String>, Arc<dyn Component<T>>);
type ComponentWithID<T, E> = (Option<String>, Arc<dyn Component<T, E>>);
pub struct ActionRow<T> {
components: Vec<ComponentWithID<T>>,
pub struct ActionRow<T, E> {
components: Vec<ComponentWithID<T, E>>,
}
impl<T> ActionRow<T> {
pub fn new(components: &[ComponentWithID<T>]) -> Self {
impl<T, E> ActionRow<T, E> {
pub fn new(components: &[ComponentWithID<T, E>]) -> Self {
Self {
components: components.to_vec(),
}
}
pub fn add(&mut self, id: Option<String>, component: Arc<dyn Component<T>>) {
pub fn add(&mut self, id: Option<String>, component: Arc<dyn Component<T, E>>) {
self.components.push((id, component));
}
@@ -41,19 +43,21 @@ impl<T> ActionRow<T> {
}
#[async_trait]
pub trait Component<T>: Send + Sync + Debug {
pub trait Component<T, E>: Send + Sync + Debug {
fn custom_id(&self) -> Option<String> {
Some(String::from("component"))
}
fn build(&self, id: Option<String>) -> TwilightComponent;
async fn execute(&self, ctx: InteractionContext<T>) -> Result<(), InteractionError>;
async fn execute(&self, ctx: InteractionContext<T, E>) -> Result<(), InteractionError>;
}
#[async_trait]
impl<T, S: Send + Sync + 'static> Component<S> for T
impl<T, S, E> Component<S, E> for T
where
T: Button<S>,
T: Button<S, E>,
S: Send + Sync + 'static,
E: Send + Sync + 'static,
{
fn custom_id(&self) -> Option<String> {
Button::id(self)
@@ -62,7 +66,7 @@ where
fn build(&self, id: Option<String>) -> TwilightComponent {
TwilightComponent::Button(TwilightButton {
custom_id: id,
disabled: false,
disabled: self.disabled(),
emoji: None,
label: self.label().map(|i| i.to_string()),
style: if self.url().is_none() {
@@ -75,13 +79,17 @@ where
})
}
async fn execute(&self, ctx: InteractionContext<S>) -> Result<(), InteractionError> {
async fn execute(&self, ctx: InteractionContext<S, E>) -> Result<(), InteractionError> {
self.on_press(ctx).await
}
}
#[async_trait]
pub trait Button<S: Send + Sync + 'static>: Send + Sync + Debug {
pub trait Button<S, E>: Send + Sync + Debug
where
S: Send + Sync + 'static,
E: Send + Sync + 'static,
{
fn id(&self) -> Option<String> {
if self.url().is_none() {
Some(String::from("Button"))
@@ -89,17 +97,24 @@ pub trait Button<S: Send + Sync + 'static>: Send + Sync + Debug {
None
}
}
fn style(&self) -> ButtonStyle {
ButtonStyle::Secondary
}
fn label(&self) -> Option<&'static str> {
None
}
fn url(&self) -> Option<&'static str> {
fn label(&self) -> Option<String> {
None
}
async fn on_press(&self, ctx: InteractionContext<S>) -> Result<(), InteractionError> {
fn url(&self) -> Option<String> {
None
}
fn disabled(&self) -> bool {
false
}
async fn on_press(&self, ctx: InteractionContext<S, E>) -> Result<(), InteractionError> {
ctx.defer().await
}
}
+105 -40
View File
@@ -1,24 +1,40 @@
use std::sync::Arc;
use twilight_model::{
gateway::payload::incoming::InteractionCreate,
http::interaction::{InteractionResponse, InteractionResponseType},
id::{Id, marker::InteractionMarker},
};
use twilight_http::response::marker::EmptyBody;
use twilight_http::{Error, Response};
use twilight_model::gateway::payload::incoming::InteractionCreate;
use twilight_model::http::interaction::{InteractionResponse, InteractionResponseType};
use twilight_util::builder::InteractionResponseDataBuilder;
use crate::framework::{
commands::messages::OriginalMessageUpdater, interactions::InteractionError, runtime::Runtime,
};
use crate::framework::interactions::InteractionError;
use crate::framework::interactions::components::ActionRow;
use crate::framework::messages::MessageEditBuilder;
use crate::framework::runtime::Runtime;
pub struct InteractionContext<T> {
pub struct InteractionContext<T, E> {
pub event: InteractionCreate,
pub rt: Arc<Runtime<T>>,
pub rt: Arc<Runtime<T, E>>,
pub prefix: String,
pub extras: E,
}
impl<T> InteractionContext<T> {
pub fn new(event: InteractionCreate, rt: Arc<Runtime<T>>, prefix: String) -> Self {
Self { event, rt, prefix }
impl<T, E> InteractionContext<T, E>
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
pub fn new(
event: InteractionCreate,
rt: Arc<Runtime<T, E>>,
prefix: String,
extras: E,
) -> Self {
Self {
event,
rt,
prefix,
extras,
}
}
pub async fn defer(&self) -> Result<(), InteractionError> {
@@ -33,36 +49,85 @@ impl<T> InteractionContext<T> {
kind: InteractionResponseType::DeferredUpdateMessage,
},
)
.await
.map_err(|_| InteractionError::DeferringFailed)?;
.await?;
Ok(())
}
pub fn original_message(&self) -> Option<OriginalMessage<T>> {
self.event.message.as_ref().map(|_| OriginalMessage {
interaction_id: self.event.id,
interaction_token: self.event.token.clone(),
rt: self.rt.clone(),
})
}
}
pub struct OriginalMessage<T> {
interaction_id: Id<InteractionMarker>,
interaction_token: String,
rt: Arc<Runtime<T>>,
}
impl<T> OriginalMessage<T>
where
T: Send + Sync + 'static,
{
pub fn edit(&self) -> OriginalMessageUpdater<T> {
OriginalMessageUpdater::new(
self.interaction_id,
self.interaction_token.clone(),
self.rt.clone(),
)
pub async fn edit_original_message(
&self,
builder: MessageEditBuilder<T, E>,
) -> Result<Response<EmptyBody>, Error> {
let mut sender = InteractionResponseDataBuilder::new();
if let Some(content) = &builder.content {
if let Some(content) = content {
sender = sender.content(content);
} else {
sender = sender.content("");
}
}
let mut current_row = ActionRow::new(&[]);
let mut current_index = 0;
let mut custom_ids: Vec<String> = vec![];
if let Some(components) = builder.components {
let mut rows = vec![];
for (component, index) in components {
if index != current_index {
if !current_row.is_empty() {
rows.push(current_row.build());
current_row = ActionRow::new(&[]);
}
current_index += 1;
}
let custom_id = component.custom_id();
if let Some(custom_id) = &custom_id {
custom_ids.push(custom_id.clone());
self.rt.registry.register(custom_id, component.clone());
}
current_row.add(custom_id.clone(), component.clone());
}
if !current_row.is_empty() {
rows.push(current_row.build());
}
sender = sender.components(rows);
}
if let Some(embeds) = builder.embeds {
sender = sender.embeds(embeds);
}
let result = self
.rt
.http
.interaction(self.rt.app.id)
.create_response(
self.event.id,
&self.event.token,
&InteractionResponse {
data: Some(sender.build()),
kind: InteractionResponseType::UpdateMessage,
},
)
.await;
if result.is_err() {
for custom_id in custom_ids {
self.rt.registry.unregister(custom_id);
}
}
result
}
}
+11 -3
View File
@@ -1,5 +1,7 @@
use thiserror::Error;
use crate::database::models::DatabaseError;
pub mod components;
pub mod context;
pub mod registry;
@@ -12,9 +14,6 @@ pub enum InteractionError {
)]
InteractionNotFound,
#[error("The interaction was attempted to be deferred, but it failed to be done")]
DeferringFailed,
#[error("Discord responded with an interaction type Payphone does not use")]
InteractionTypeUnsent,
@@ -23,4 +22,13 @@ pub enum InteractionError {
#[error("No prefixes were returned for the event")]
PrefixesVectorEmpty,
#[error("The extras getter failed to retrieve extras")]
ExtrasGetterFailed,
#[error(transparent)]
DatabaseError(#[from] DatabaseError),
#[error(transparent)]
DiscordAPIError(#[from] twilight_http::Error),
}
+31 -15
View File
@@ -1,26 +1,24 @@
use std::sync::Arc;
use scc::HashMap;
use twilight_model::{
application::interaction::InteractionData, gateway::payload::incoming::InteractionCreate,
};
use crate::framework::{
interactions::{InteractionError, context::InteractionContext},
runtime::Runtime,
};
use twilight_model::application::interaction::InteractionData;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use super::components::Component;
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::interactions::InteractionError;
use crate::framework::interactions::context::InteractionContext;
use crate::framework::runtime::Runtime;
#[derive(Default)]
pub struct ComponentRegistry<T> {
inner: HashMap<String, Arc<dyn Component<T>>>,
pub struct ComponentRegistry<T, E> {
inner: HashMap<String, Arc<dyn Component<T, E>>>,
}
impl<T> ComponentRegistry<T>
impl<T, E> ComponentRegistry<T, E>
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
pub fn new() -> Self {
Self {
@@ -28,7 +26,7 @@ where
}
}
pub fn register(&self, id: impl ToString, component: Arc<dyn Component<T>>) {
pub fn register(&self, id: impl ToString, component: Arc<dyn Component<T, E>>) {
self.inner.upsert(id.to_string(), component);
}
@@ -39,12 +37,16 @@ where
pub async fn execute(
&self,
event: &InteractionCreate,
rt: Arc<Runtime<T>>,
rt: Arc<Runtime<T, E>>,
extras: Arc<dyn ExtrasGetter<T, Extras = E>>,
) -> Result<(), InteractionError> {
if let Some(data) = &event.data {
match data {
InteractionData::MessageComponent(data) => {
if let Some(component) = self.inner.get_async(&data.custom_id).await {
if let Some(guarded_component) = self.inner.get(&data.custom_id) {
let component = guarded_component.clone();
drop(guarded_component);
let prefixes = rt
.get_prefixes(
event.guild_id.map(|id| id.get()),
@@ -55,13 +57,27 @@ where
.first()
.ok_or(InteractionError::PrefixesVectorEmpty)?;
let extras = extras
.get_extra(
event.author().expect("Component interaction had no author"),
&rt,
)
.await
.inspect_err(|e| {
log::error!("Failed to get extras for component interaction: {e:?}")
})
.map_err(|_| InteractionError::ExtrasGetterFailed)?;
component
.execute(InteractionContext::new(
event.clone(),
rt.clone(),
prefix.to_string(),
extras,
))
.await
.inspect(|_| log::debug!("Executed component interaction"))
.inspect_err(|e| log::error!("Interaction execution failed: {e:?}"))
} else {
Err(InteractionError::InteractionNotFound)
}
+12 -7
View File
@@ -3,20 +3,25 @@ use std::sync::Arc;
use async_trait::async_trait;
use twilight_model::gateway::payload::incoming::InteractionCreate;
use crate::framework::{
events::traits::{EventResult, OnInteractionHandler},
runtime::Runtime,
};
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::events::traits::{EventResult, OnInteractionHandler};
use crate::framework::runtime::Runtime;
#[derive(Debug)]
pub struct InteractionRunner;
#[async_trait]
impl<T> OnInteractionHandler<T> for InteractionRunner
impl<T, E> OnInteractionHandler<T, E> for InteractionRunner
where
T: Send + Sync + 'static,
E: Send + Sync + 'static,
{
async fn on_interaction(&self, event: &InteractionCreate, rt: Arc<Runtime<T>>) -> EventResult {
Ok(rt.registry.execute(event, rt.clone()).await?)
async fn on_interaction(
&self,
event: &InteractionCreate,
rt: Arc<Runtime<T, E>>,
extras: Arc<dyn ExtrasGetter<T, Extras = E>>,
) -> EventResult {
Ok(rt.registry.execute(event, rt.clone(), extras).await?)
}
}
+96
View File
@@ -0,0 +1,96 @@
use std::sync::Arc;
use twilight_model::channel::message::Embed;
use crate::framework::interactions::components::Component;
type ComponentWithRowIndex<S, E> = (Arc<dyn Component<S, E>>, usize);
pub struct MessageBuilder<S, E> {
pub content: Option<String>,
pub embeds: Vec<Embed>,
pub components: Vec<ComponentWithRowIndex<S, E>>,
}
impl<S, E> MessageBuilder<S, E> {
pub fn new() -> Self {
Self {
content: None,
embeds: Vec::new(),
components: Vec::new(),
}
}
pub fn content(mut self, content: impl Into<String>) -> Self {
self.content = Some(content.into());
self
}
pub fn embed(mut self, embed: Embed) -> Self {
self.embeds.push(embed);
self
}
pub fn component(mut self, component: impl Component<S, E> + 'static, row: usize) -> Self {
self.components.push((Arc::new(component), row));
self
}
}
pub struct MessageEditBuilder<S, E> {
pub content: Option<Option<String>>,
pub embeds: Option<Vec<Embed>>,
pub components: Option<Vec<ComponentWithRowIndex<S, E>>>,
}
impl<S, E> MessageEditBuilder<S, E> {
pub fn new() -> Self {
Self {
content: None,
embeds: None,
components: None,
}
}
pub fn content(mut self, content: impl Into<String>) -> Self {
self.content = Some(Some(content.into()));
self
}
pub fn embed(mut self, embed: Embed) -> Self {
if self.embeds.is_none() {
self.embeds = Some(Vec::new());
}
self.embeds.as_mut().unwrap().push(embed);
self
}
pub fn component(mut self, component: impl Component<S, E> + 'static, row: usize) -> Self {
if self.components.is_none() {
self.components = Some(Vec::new());
}
self.components
.as_mut()
.unwrap()
.push((Arc::new(component), row));
self
}
}
impl<S, E> From<MessageBuilder<S, E>> for MessageEditBuilder<S, E> {
fn from(builder: MessageBuilder<S, E>) -> Self {
Self {
content: builder.content.map(Some),
embeds: Some(builder.embeds),
components: Some(builder.components),
}
}
}
+4 -5
View File
@@ -76,8 +76,7 @@
//! // Your command logic here.
//! ctx.send()
//! .content("Hello, world!")
//! .await
//! .map_err(|_| CommandError::MessageSendingFailed)?;
//! .await?;
//!
//! Ok(())
//! }
@@ -149,8 +148,7 @@
//!
//! ctx.send()
//! .content(format!("Hello, {}!", name.0))
//! .await
//! .map_err(|_| CommandError::MessageSendingFailed)?;
//! .await?;
//!
//! Ok(())
//! }
@@ -158,8 +156,9 @@
//! ```
pub mod bot;
pub mod cache;
pub mod commands;
pub mod events;
pub mod interactions;
pub mod messages;
pub mod runtime;
pub mod tasks;
+20 -9
View File
@@ -19,15 +19,18 @@
use std::sync::Arc;
use tokio::sync::mpsc::UnboundedSender;
use twilight_cache_inmemory::InMemoryCache;
use twilight_http::Client;
use twilight_model::gateway::payload::outgoing::UpdatePresence;
use twilight_model::oauth::Application;
use crate::framework::{
bot::PrefixGetter, commands::Command, interactions::registry::ComponentRegistry,
};
use crate::framework::bot::PrefixGetter;
use crate::framework::commands::Command;
use crate::framework::interactions::registry::ComponentRegistry;
/// The application's runtime tools.
pub struct Runtime<T> {
pub struct Runtime<T, E> {
/// The HTTP client used for making requests to the HTTP API.
pub http: Client,
@@ -35,19 +38,27 @@ pub struct Runtime<T> {
pub app: Application,
/// The component registry.
pub registry: ComponentRegistry<T>,
pub registry: ComponentRegistry<T, E>,
/// The command prefixes getter.
pub prefixes: Arc<dyn PrefixGetter<T> + Send + Sync + 'static>,
pub prefixes: Arc<dyn PrefixGetter<T, E> + Send + Sync + 'static>,
/// The commands available in the application.
pub commands: Vec<Arc<dyn Command<T>>>,
pub commands: Vec<Arc<dyn Command<T, E>>>,
/// The application state.
pub state: Arc<T>,
pub cache: InMemoryCache,
/// Used to send messages through the gateway.
pub gateway_tx: UnboundedSender<UpdatePresence>,
pub shard_number: u32,
pub shard_total: u32,
}
impl<T> Runtime<T> {
impl<T, E> Runtime<T, E> {
/// Get the command prefixes set for the server and user ID.
///
/// Arguments:
@@ -71,7 +82,7 @@ impl<T> Runtime<T> {
///
/// Returns:
/// [`Option<Arc<dyn Command<T>>>`] - The command if found, otherwise `None`.
pub fn get_command(&self, name: &str) -> Option<Arc<dyn Command<T>>> {
pub fn get_command(&self, name: &str) -> Option<Arc<dyn Command<T, E>>> {
self.commands
.iter()
.find(|cmd| {
+13
View File
@@ -0,0 +1,13 @@
use std::fmt::Debug;
use std::time::Duration;
use async_trait::async_trait;
use crate::framework::runtime::Runtime;
#[async_trait]
pub trait Task<S, E>: Send + Sync + Debug {
fn delay(&self) -> Duration;
async fn run(&self, rt: &Runtime<S, E>) -> anyhow::Result<()>;
}
+100 -25
View File
@@ -1,25 +1,24 @@
use async_trait::async_trait;
use crate::{
framework::commands::{
Command, CommandError,
arguments::{Argument, NeedyString, ParseArguments},
context::CommandContext,
},
groups::about::{
components::{
HelpDonateLinkButton, HelpGoBackButton, HelpSupportLinkButton, HelpWebsiteLinkButton,
},
embeds::{get_all_command_help_embed, get_command_help_embed, get_command_not_found_embed},
},
state::State,
use crate::extras::Extras;
use crate::framework::commands::arguments::{Arg, Argument, NeedyString, ParseArguments};
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::{Command, CommandError};
use crate::framework::runtime::Runtime;
use crate::groups::about::components::{
HelpDonateLinkButton, HelpGoBackButton, HelpSupportLinkButton, HelpWebsiteLinkButton,
};
use crate::groups::about::embeds::{
get_all_command_help_embed, get_command_help_embed, get_command_not_found_embed,
};
use crate::groups::calls::components::CodeOfConductButton;
use crate::state::State;
#[derive(Debug)]
pub struct HelpCommand;
#[async_trait]
impl Command<State> for HelpCommand {
impl Command<State, Extras> for HelpCommand {
fn name(&self) -> &'static str {
"help"
}
@@ -38,38 +37,114 @@ impl Command<State> for HelpCommand {
async fn execute(
&self,
ctx: CommandContext<'_, State>,
ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let command_name: Option<NeedyString> = ParseArguments::parse(args).unwrap();
let command_name = Arg::<Option<NeedyString>>::parse(args, &ctx).await.unwrap();
if let Some(command_name) = command_name {
if let Some(command_name) = command_name.0 {
if let Some(command) = ctx.rt.get_command(&command_name) {
ctx.send()
.embed(get_command_help_embed(&command, &ctx))
.component(HelpGoBackButton, 1)
.component(HelpSupportLinkButton, 1)
.await
.inspect_err(|e| log::error!("Failed to send message! {e}"))
.map_err(|_| CommandError::MessageSendingFailed)?;
.inspect_err(|e| log::error!("Failed to send message! {e}"))?;
} else {
ctx.send()
.embed(get_command_not_found_embed(ctx.rt, command_name.0))
.embed(get_command_not_found_embed(&ctx.rt, command_name.0))
.component(HelpGoBackButton, 1)
.component(HelpSupportLinkButton, 1)
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
}
} else {
ctx.send()
.embed(get_all_command_help_embed(ctx.prefix, ctx.rt))
.embed(get_all_command_help_embed(ctx.prefix, &ctx.rt, &ctx.extras))
.component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1)
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.component(CodeOfConductButton, 1)
.await?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct CodeOfConductCommand;
#[async_trait]
impl Command<State, Extras> for CodeOfConductCommand {
fn name(&self) -> &'static str {
"codeofconduct"
}
fn aliases(&self) -> &'static [&'static str] {
&["co"]
}
fn description(&self) -> &'static str {
"Shows a link to Payphone's Code of Conduct."
}
fn show_in_help(&self, _rt: &Runtime<State, Extras>, _extras: &Extras) -> bool {
false
}
fn only_runs_if_startswith(&self) -> bool {
false
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
ctx.send()
.content("<https://payphone.lat/code-of-conduct>")
.reply_to(ctx.event.id)
.await?;
Ok(())
}
}
#[derive(Debug)]
pub struct DonateCommand;
#[async_trait]
impl Command<State, Extras> for DonateCommand {
fn name(&self) -> &'static str {
"donate"
}
fn aliases(&self) -> &'static [&'static str] {
&["d"]
}
fn description(&self) -> &'static str {
"Shows a link to Payphone's Ko-Fi page."
}
fn show_in_help(&self, _rt: &Runtime<State, Extras>, _extras: &Extras) -> bool {
false
}
fn only_runs_if_startswith(&self) -> bool {
false
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
ctx.send()
.reply_to(ctx.event.id)
.content("<https://ko-fi.com/payphonedev>")
.await?;
Ok(())
}
}
+46 -38
View File
@@ -1,32 +1,40 @@
use async_trait::async_trait;
use crate::{
framework::interactions::{InteractionError, components::Button, context::InteractionContext},
groups::about::embeds::get_all_command_help_embed,
state::State,
};
use crate::extras::Extras;
use crate::framework::interactions::InteractionError;
use crate::framework::interactions::components::Button;
use crate::framework::interactions::context::InteractionContext;
use crate::framework::messages::MessageEditBuilder;
use crate::groups::about::embeds::get_all_command_help_embed;
use crate::state::State;
#[derive(Debug)]
pub struct HelpGoBackButton;
#[async_trait]
impl Button<State> for HelpGoBackButton {
fn label(&self) -> Option<&'static str> {
Some("← Go back to commands list")
impl Button<State, Extras> for HelpGoBackButton {
fn id(&self) -> Option<String> {
Some("help:go-back".into())
}
async fn on_press(&self, ctx: InteractionContext<State>) -> Result<(), InteractionError> {
fn label(&self) -> Option<String> {
Some("← Go back to commands list".into())
}
async fn on_press(
&self,
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
ctx
.original_message()
.expect(
"Buttons always have the original message in the interaction context, this one didn't (got None)"
.edit_original_message(
MessageEditBuilder::new().embed(
get_all_command_help_embed(&ctx.prefix, &ctx.rt, &ctx.extras)
)
.component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1)
.component(CodeOfConductLinkButton, 1)
)
.edit()
.embed(get_all_command_help_embed(&ctx.prefix, ctx.rt))
.component(HelpWebsiteLinkButton, 1)
.component(HelpSupportLinkButton, 1)
.component(HelpDonateLinkButton, 1)
.component(CodeOfConductLinkButton, 1)
.await
.inspect_err(|e| log::error!("An error occurred while attempting to edit the original message of an interaction. {e:?}"))
.map_err(
@@ -41,13 +49,13 @@ impl Button<State> for HelpGoBackButton {
pub struct HelpSupportLinkButton;
#[async_trait]
impl Button<State> for HelpSupportLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Get help")
impl Button<State, Extras> for HelpSupportLinkButton {
fn label(&self) -> Option<String> {
Some("Get help".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://discord.gg/9daSsrfTmE")
fn url(&self) -> Option<String> {
Some("https://discord.gg/9daSsrfTmE".into())
}
}
@@ -55,13 +63,13 @@ impl Button<State> for HelpSupportLinkButton {
pub struct HelpWebsiteLinkButton;
#[async_trait]
impl Button<State> for HelpWebsiteLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Website")
impl Button<State, Extras> for HelpWebsiteLinkButton {
fn label(&self) -> Option<String> {
Some("Website".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://payphone.lat/")
fn url(&self) -> Option<String> {
Some("https://payphone.lat/".into())
}
}
@@ -69,13 +77,13 @@ impl Button<State> for HelpWebsiteLinkButton {
pub struct HelpDonateLinkButton;
#[async_trait]
impl Button<State> for HelpDonateLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Donate")
impl Button<State, Extras> for HelpDonateLinkButton {
fn label(&self) -> Option<String> {
Some("Donate".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://ko-fi.com/payphonedev")
fn url(&self) -> Option<String> {
Some("https://ko-fi.com/payphonedev".into())
}
}
@@ -83,12 +91,12 @@ impl Button<State> for HelpDonateLinkButton {
pub struct CodeOfConductLinkButton;
#[async_trait]
impl Button<State> for CodeOfConductLinkButton {
fn label(&self) -> Option<&'static str> {
Some("Code of Conduct")
impl Button<State, Extras> for CodeOfConductLinkButton {
fn label(&self) -> Option<String> {
Some("Code of Conduct".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://payphone.lat/code-of-conduct")
fn url(&self) -> Option<String> {
Some("https://payphone.lat/code-of-conduct".into())
}
}
+29 -18
View File
@@ -5,20 +5,19 @@ use twilight_util::builder::embed::{
EmbedAuthorBuilder, EmbedBuilder, EmbedFieldBuilder, EmbedFooterBuilder, ImageSource,
};
use crate::{
constants::{COLOR_RED, COLOR_WHITE},
discord::{images, sanitizing::SanitizeDiscordMarkdown},
framework::{
commands::{Command, context::CommandContext},
runtime::Runtime,
},
state::State,
utils::ToTitleCase,
};
use crate::constants::{COLOR_RED, COLOR_WHITE, VERSION};
use crate::discord::images;
use crate::discord::sanitizing::SanitizeDiscordMarkdown;
use crate::extras::Extras;
use crate::framework::commands::Command;
use crate::framework::commands::context::CommandContext;
use crate::framework::runtime::Runtime;
use crate::state::State;
use crate::utils::ToTitleCase;
pub(super) fn get_command_help_embed(
command: &Arc<dyn Command<State>>,
ctx: &CommandContext<'_, State>,
command: &Arc<dyn Command<State, Extras>>,
ctx: &CommandContext<'_, State, Extras>,
) -> Embed {
let name = format!("{}{}", ctx.prefix, command.name());
let arguments = command
@@ -42,6 +41,7 @@ pub(super) fn get_command_help_embed(
ctx.rt.app.bot.as_ref().unwrap().avatar,
ctx.rt.app.bot.as_ref().unwrap().id.get(),
ctx.rt.app.bot.as_ref().unwrap().discriminator as u64,
None,
))
.unwrap(),
)
@@ -52,6 +52,7 @@ pub(super) fn get_command_help_embed(
ctx.rt.app.bot.as_ref().unwrap().avatar,
ctx.rt.app.bot.as_ref().unwrap().id.get(),
ctx.rt.app.bot.as_ref().unwrap().discriminator as u64,
None,
))
.unwrap(),
)
@@ -79,12 +80,17 @@ pub(super) fn get_command_help_embed(
.build()
}
pub(super) fn get_all_command_help_embed<T>(prefix: &str, rt: Arc<Runtime<T>>) -> Embed {
pub(super) fn get_all_command_help_embed(
prefix: &str,
rt: &Runtime<State, Extras>,
extras: &Extras,
) -> Embed {
EmbedBuilder::new()
.author(EmbedAuthorBuilder::new(rt.app.name.clone()).icon_url(ImageSource::url(images::get_avatar_url(
rt.app.bot.as_ref().unwrap().avatar,
rt.app.bot.as_ref().unwrap().id.get(),
rt.app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap()))
.title("Pick up the phone and start making friends!")
@@ -93,31 +99,35 @@ pub(super) fn get_all_command_help_embed<T>(prefix: &str, rt: Arc<Runtime<T>>) -
rt.app.bot.as_ref().unwrap().avatar,
rt.app.bot.as_ref().unwrap().id.get(),
rt.app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap())
.color(COLOR_WHITE)
.field(EmbedFieldBuilder::new("Commands", get_commands_table(rt)).build())
.footer(EmbedFooterBuilder::new(format!("v{} - Use {}help <command> to get more information about a specific command.", env!("CARGO_PKG_VERSION"), prefix)))
.field(EmbedFieldBuilder::new("Commands", get_commands_table(rt, extras)).build())
.footer(EmbedFooterBuilder::new(format!("v{VERSION}-{} - Use {}help <command> to get more information about a specific command.", rt.shard_number + 1, prefix)))
.build()
}
pub(super) fn get_commands_table<T>(rt: Arc<Runtime<T>>) -> String {
pub(super) fn get_commands_table<T>(rt: &Runtime<T, Extras>, extras: &Extras) -> String {
let mut table = String::new();
for command in rt.commands.iter() {
table.push_str(&format!("{:<12}", command.name()));
if command.show_in_help(rt, extras) {
table.push_str(&format!("{:<13}", command.name()));
}
}
format!("```\n{table}\n```")
}
pub(super) fn get_command_not_found_embed<T>(rt: Arc<Runtime<T>>, name: String) -> Embed {
pub(super) fn get_command_not_found_embed<T>(rt: &Runtime<T, Extras>, name: String) -> Embed {
EmbedBuilder::new()
.color(COLOR_RED)
.author(EmbedAuthorBuilder::new(rt.app.name.clone()).icon_url(ImageSource::url(images::get_avatar_url(
rt.app.bot.as_ref().unwrap().avatar,
rt.app.bot.as_ref().unwrap().id.get(),
rt.app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap()))
.title("That's not a command")
@@ -126,6 +136,7 @@ pub(super) fn get_command_not_found_embed<T>(rt: Arc<Runtime<T>>, name: String)
rt.app.bot.as_ref().unwrap().avatar,
rt.app.bot.as_ref().unwrap().id.get(),
rt.app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap())
.build()
+1
View File
@@ -1,3 +1,4 @@
pub mod commands;
pub mod components;
pub mod embeds;
pub mod tasks;
+267
View File
@@ -0,0 +1,267 @@
use async_trait::async_trait;
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;
use twilight_model::gateway::payload::outgoing::UpdatePresence;
use twilight_model::gateway::presence::{Activity, ActivityType, Status};
use crate::extras::Extras;
use crate::framework::runtime::Runtime;
use crate::framework::tasks::Task;
use crate::state::State;
#[derive(Debug)]
pub struct UpdatePresenceTask;
#[async_trait]
impl Task<State, Extras> for UpdatePresenceTask {
fn delay(&self) -> std::time::Duration {
std::time::Duration::from_secs(120)
}
async fn run(&self, rt: &Runtime<State, Extras>) -> anyhow::Result<()> {
let presences = vec![
"Billie Jean is not my lover",
"Baby vamo' a buscar una excusa para vernos",
"Vi que estaba sola y que queria bellaquear",
"Esto es real gangsta love",
"Dice que está acompañada, pero sé que en el fondo ella se encuentra sola",
"Conmigo todo eso ignora, bailando se van las horas",
"Me dice 'I wanna know you more', pero no logro entenderte",
"Tiene una amiga que le traduce, ella sola se lo introduce",
"Y aunque intentara olvidarte, mi boca no lo haría",
"Qué más da si besarte es tan fácil",
"Quería olvidarte, no lo logré, pero casi",
"Tú no me dejas en paz, de mi mente no te vas",
"No me busque' en Instagram, mami, búscame en casa",
"Dime dónde tú está', que yo por ti cojo un vuelo, y a Yonaguni le llego",
"Masivo, we run the world (da-ddy)",
"Vamos cógele el ritmo, cintura, rodilla al piso",
"Oh-eh-oh, mano arriba, no la dejes caer",
"Y esto está como, como pa, como pa, como pa rumbiar, pa pasarla caliente, con toda mi gente",
"Nos favorece el sol, tu bronceado y el calor",
"Porque hoy hace caloooor, hace un re caloooor",
"Tan bonita como tu, tan bonita y sola",
"Te he visto antes, te pareces al amor de mi vida",
"Tú está' como pa' mete-, pa' meterte el cora'",
"Whine up, whine up, whine up, mami baila, baila-a",
"Esto es pa que baile'-e'-e', mueve la cintura y dale pa'l suelo",
"Para todo' eso' amore que, que fueron obligados a ser separados",
"Dime ¿Cómo le explico a mi destino que ya no estás ahí?",
"Eres la niña de mis ojos, tú, eres todo lo que quiero yo",
"Las tentacione' así como tú merecen pecado' como yo",
"Ay, tienes la magia, tú sí tienes una vainita que a mí me encanta, me enloquece",
"Ay tú no me dices que sí, que sí que sí que sí",
"Si tú me dices ahorita que me quieres a tu la'o que lindo sería",
"La gente me dice que ya es muy obvio que ya se me nota",
"Si tú supieras que por ti me muero, que yo te quiero",
"Si tú supieras lo que te esperado, que yo te amo",
"Y me dijeron que te vieron sola ¿Por qué estás sola?",
"Ella está recién soltera, de hace poquito",
"El pelo se lo suelta, el vestido cortito",
"Si yo no te escribo, tú no me escribe'",
"Negra, rara vez te vi bien tando con aquel",
"Te estoy viendo de hace un tiempo, 'toy esperando el momento, ma', no paro de pensarte, ¿qué le voy a hacer?",
"Antes que te vayas dame un beso",
"C'mon (Oh oh oh oh oh oh), Daddy (Oh oh oh oh oh oh)",
"Y el día está soleao, te quiero de mi lao",
"Baby, te vo'a dar una vuelta por la playita",
"Aquella noche que volviste, llorando me convenciste",
"Malo, malo, pero malo",
"Goin' deep in with me for no reason",
"It ain't no problem, it's cool to do it in the night",
"You give me your love, but it's borrowed",
"Y no colme la paciencia si no quieres tu demencia",
"Tengo su criptonita, y para sus mujeres les tengo una vitamina",
"Sólo somos tú y yo",
"Llegó el tiempo de los dos",
"De verdad tienes lo que me gusta a mí",
"Al ritmo y al movimiento, le ponemos sentimiento",
"Tú eres hielo, yo soy fuego, vamo' a ver quién se va a quemar",
"Bailando así pidiendo más y más calor",
"Rumba pa' que tú abuses, BUM!",
"Nueva temporada ya empezó, dale play",
"Sonido del bajo, Bizarrap, suena el bass",
"Si me preguntan, a nadie yo le debo",
"Ahora estoy buscando algo más, una razón para volverme a enamorar (puede que seas tú)",
"Quiero una chica, quiero una gyal",
"Que-que-que no diga que no, que no, que no, que no, que no, que",
"Me monté en un barco, he cruzado el mar, he subido el río",
"Le digo hola, ella me dice goodbye",
"Si yo le salgo por la izquierda, se va pa' la derecha",
"No se lo que le pasa, conmigo ella no quiere bailar",
"Yo quería decirle que me encanta",
"Una varita diseño su cuerpo",
"Y la verdad, si está mas buena, explota",
"Baby yo llevo tiempo deseandote aquí",
"Tiraré la casa por la ventana",
"Y no te importa cuantos caigan por error",
"Presiento que tu siempre vas y vienes",
"Presiento que serás de esos errores que estoy dispuesto a cometer",
"Podré vivir sin escuchar tu voz",
"Bebé, me enteré que con ella peleaste",
"Y a estas alturas no importa si estás con él",
"La luna llena alumbrandote",
"Cuando te vi, supe que iba a pasar",
"Que me gustas mucho con bastante",
"En la radio, tu song favorito",
"Como mango y limón, saborearte",
"Tú eres la dulce fruta que mi paladar añora",
"Esa cara de ternura sé que esconde una atrevida",
"Teresa es una asesina, que cuando camina la ven y dicen oooh",
"Y no le importa si el novio le corta, se corta una botella y se va para el club",
"Essa novinha é terrorista, é especialista",
"Olha o que ela faz num baile funk com as amiga",
"Cara de doncella, pero mas bestia que bella",
"Si me avisa en cinco estoy, porque sabe como soy",
"Su gato no le da, entonces me llama y voy",
"Se te nota que quieres de mi boca",
"Si hay rumba no quiero mas na'",
"Yo lo que vine es a pasarla bien",
"Ella no e' tuya, te vendió sueño, ey, dice que no tiene dueño",
"Te está haciendo lucir mal, manito; yo que tú, ruedo",
"Los besos no se dan, se roban",
"Yo tengo tu amor, I got your love",
"Como ríe la vida si tus ojos negros me quieren mirar",
"El día que me quieras la rosa que engalana se vestirá de fiesta con su mejor color",
"Luciérnagas curiosas que verán que eres mi consuelo",
"DANZA KUDUROOOOOO",
"La mano arriba, cintura sola, da media vuelta, danza kuduro",
"¿Quién puede domar la fuerza del mal que se mete por tus vena'?",
"¿Quién puede parar eso que al bailar descontrola tu cadera?",
"Hey DJ, póngale la música que le gusta",
"Y cómo hago con mi mente pa' decirle que los momentos que tuvimos se quedan en la nada",
"No necesito quejas, sino contención",
"Cómo hago pa' mentirme diciéndome que no quiero verte aunque extrañe tu cara",
"Y no puedo sacarte de mi mente, y no quiero hablar con otra gente",
"Y si tengo que escoger, me quedo, me quedo contigo",
"Y si yo vuelvo a San Juan, yo bailo, yo bailo contigo",
"Y si te tengo que olvidar, tú sabe' que no va a pasar",
"Contigo desde Alaska hasta Buenos Aires",
"There on the subway, I nearly had a breakdown",
"Tú no fuiste la primera, tampoco serás la última",
"He giving me that good shit, that make me not quit",
"Oh, he give it to me everyday, everyday, everyday",
"You just want attention, you don't want my heart",
"Maybe you just hate the thought of me with someone new",
"Y la vi, que va a ser, una hermosa lucifer",
"Y es que este amor es azul como el mar azul",
"Como de tu mirada nació mi ilusión",
"Fue una mañana que yo te encontré, cuando la brisa besaba tu dulce piel",
"Tus ojos tristes que al ver adoré, la noche que yo te amé, azul",
"Hoy miro al cielo y en ti puedo ver, la estrella que siempre soñé (azul)",
"Eres la niña que siempre busqué, azul",
"Es tu inocencia que quiero entender",
"Y con la lluvia pintada de azul, por siempre serás solo tú",
"Azul como el lucero de nuestra pasión",
"I heard the music through the walls",
"I felt you here before I even saw your face",
"Though we can't get higher",
"But we keep going up, going up, going up, going up, going up",
"They could describe everything with one single word",
"Eres lo primero que yo pienso cuando alguien me dice 'pide un deseo'",
"Tengamos algo sin mentiras",
"Y ya sé que estás aburrida de promesas incumplidas",
"Quiero que tu seas mi princesa",
"I wanna let my hair down while I'm staring down your face",
"Que lindo que te queda ese look bronceado",
"Si tú me bailas así yo me muero de amor",
"Boy, don't make me choose",
"We can share one seat",
"I think you wanna uh",
"I think you know what this is",
"Pretty blue streetlights",
"In a room full of people I look at you",
"Somos dos desconocidos que se quieren conocer muy bien",
"Frequentemos nuestros cuerpos para ver que tal nos va",
"Nena, yo quiero con usted ser caballero",
"Deja que pase, pues que pase, lo que tenga que pasar",
"Todo casual, nada ideal, medio eventual, casi ilegal",
"Mami, long time sin saber de ti",
"Un brindis, vasitos arriba, y tú te pones loquita, mamita",
"Estoy ansioso por estar solos tú y yo",
"Good girl, I know you want it",
"I know you want it, you're a good girl (oh yeah)",
"Baby, it's in your nature (meow)",
"The way you grab me, must wanna get nasty",
"What do they make dreams for?",
"Ella sale por deporte, por la' noches",
"Sé muy dentro que yo sin ti estoy mejor",
"Oye, escucha lo que tengo que decir",
"Que sea así nomá y en no má' de seis tomas",
"Ya no me seduce la que se produce toda",
"Creo que me aburre lo que hoy produce la moda",
"Tu sonrisa rota me trastorna todavía",
"Vuelvo por necesidad de algo real y recíproco",
"Yo lo sentí en un segundo, me enamoré de primero",
"Tú te quedaste callada, y yo te dije te quiero",
"Imaginando de esos besos tuyos, porque no tengo de esos besos tuyos",
"Y mientras me enamoraba dijiste que había un tercero",
"Y aunque sé bien que si no hay otra voy a buscarte en otra boca",
"Como te extraño nena, no sabés",
"Me siento fuerte y débil a la vez",
"Quizá eso sea el amor",
"Dímelo si el cabrón no vale la pena y lo borramos de la escena",
"Confiesalo",
"Seeing you tonight, it's a bad idea, right?",
"You know what would be really fucking cool on this? Sabrina",
"She was covered in leather and gold",
"Little Miss Perfect sitting at the train stop",
"She's, somewhere, somewhere, somewhere in Brooklyn",
"Before I got her name, along came a train",
"Next stop, Brooklyn",
"Y si te invito a una copa, y me acerco a tu boca",
"Y si te robo un besito, a ver, ¿te enojas conmigo?",
"Una aventura es más divertida si huele a peligro",
"That's when the taxi man turned on the radio and a Jay-Z song was on",
"I'm nodding my head like, yeah, moving my hips like, yeah",
"Yeah, it's a party in the U.S.A.",
"Just shoot for the stars if it feels right",
"And aim for my heart if you feel like it",
"You say I'm a kid, my ego is big, I don't give a shit",
"Cuando se apaga la luz",
"Annie, are you ok?",
"Will you tell us that you're ok?",
"Life's like a road that you travel on",
"Life is a highway, I wanna ride it all night long",
"I wanna drive it all night long (all night long)",
"Tu cuerpo y el mío, llenando el vacío, subiendo y bajando",
"Yo quiero estar contigo, vivir contigo, bailar contigo, tener contigo una noche loca",
"But let me stop you there, oh, before you speak",
"Nah to the ah to the, no, no, no",
"My name is no, my sign is no, my number is no",
"If that boy ain't giving up, lick your lips and swing your hips",
];
let mut rng = ChaCha20Rng::from_os_rng();
let index = rng.random_range(0..presences.len());
rt.gateway_tx.send(UpdatePresence::new(
vec![Activity {
application_id: None,
assets: None,
buttons: vec![],
created_at: None,
details: None,
emoji: None,
flags: None,
id: None,
instance: None,
kind: ActivityType::Listening,
name: format!(
"p.help - {} - {}/{}",
presences[index], rt.shard_number, rt.shard_total
),
party: None,
secrets: None,
state: None,
timestamps: None,
url: None,
}],
false,
None,
Status::Online,
)?)?;
Ok(())
}
}
+310 -102
View File
@@ -1,17 +1,27 @@
use async_trait::async_trait;
use deadpool_redis::redis::AsyncTypedCommands;
use scc::HashSet;
use time::UtcDateTime;
use twilight_model::id::Id;
use crate::{
database::models::{Call, Channel},
discord::sanitizing::SanitizeDiscordMarkdown,
framework::commands::{
Command, CommandError, context::CommandContext, permissions::Permission,
},
groups::calls::{get_display_profile, permissions::NotBannedPermission},
state::State,
utils::Bye,
use crate::database::models::{Call, Channel, Participant};
use crate::discord::sanitizing::SanitizeDiscordMarkdown;
use crate::extras::Extras;
use crate::framework::commands::arguments::{Arg, Argument, ParseArguments};
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::framework::commands::{Command, CommandError};
use crate::groups::calls::masks::{get_mask_display_name, get_mask_emoji};
use crate::groups::calls::permissions::{
IsCallParticipantPermission, NonNewAccountPermission, NotBannedPermission,
};
use crate::groups::calls::strings::{
get_string_call_answered, get_string_call_hangup_other_party,
get_string_call_hangup_this_party, get_string_call_no_answer, get_string_call_searching,
get_string_tips,
};
use crate::state::State;
use crate::utils::Bye;
#[derive(Default, Debug)]
pub struct CallCommand {
@@ -31,7 +41,7 @@ impl CallCommand {
}
#[async_trait]
impl Command<State> for CallCommand {
impl Command<State, Extras> for CallCommand {
fn name(&self) -> &'static str {
"call"
}
@@ -40,13 +50,16 @@ impl Command<State> for CallCommand {
&["c"]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State> + Send + Sync + 'static>> {
vec![Box::new(NotBannedPermission)]
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![
Box::new(NotBannedPermission),
Box::new(NonNewAccountPermission),
]
}
async fn execute(
&self,
ctx: CommandContext<'_, State>,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
let channel = Channel::get_or_create_by_id(
@@ -57,8 +70,7 @@ impl Command<State> for CallCommand {
.await
.inspect_err(|e| {
log::error!("Failed to get or create channel: {e:?}");
})
.map_err(|_| CommandError::DatabaseQueryFailed)?;
})?;
if channel.is_searching || self.channel_lock.contains(&ctx.event.channel_id.get()) {
ctx.send()
@@ -66,8 +78,7 @@ impl Command<State> for CallCommand {
"☎️ You are already searching for a call! Use `{}hangup` to hang up the phone.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -76,41 +87,66 @@ impl Command<State> for CallCommand {
ctx.send()
.content(format!("☎️ You are already on a call! Use `{}hangup` to hang up the phone, or `{}skip` to skip to the next call.", ctx.prefix, ctx.prefix))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
?;
return Ok(());
}
self.channel_lock
.insert_async(ctx.event.channel_id.get())
.await
.bye();
self.channel_lock.insert(ctx.event.channel_id.get()).bye();
let call = Call::start(&channel, &ctx.rt.state.db)
.await
.inspect_err(|e| {
log::error!("Failed to start call: {e:?}");
self.channel_lock.remove(&ctx.event.channel_id.get());
})
.map_err(|_| CommandError::DatabaseQueryFailed)?;
})?;
self.channel_lock
.remove_async(&ctx.event.channel_id.get())
.await;
self.channel_lock.remove(&ctx.event.channel_id.get());
if let Some(call) = call {
ctx.send().content("☎️ Call connected. Say hi!").await.bye();
ctx.send()
.content(format!(
"**TIP:** {}\n☎️ {}\n☎️ {}",
get_string_tips(ctx.prefix),
get_string_call_searching(ctx.prefix),
get_string_call_answered(ctx.prefix)
))
.await
.bye();
ctx.rt
.http
.create_message(Id::new(call.other_party_channel_id(channel.id)))
.content("☎️ Call connected. Say hi!")
.content(&format!("☎️ {}", get_string_call_answered(ctx.prefix)))
.await
.bye();
let mut redis = ctx.rt.state.redis.get().await?;
let timestamp = UtcDateTime::now().unix_timestamp();
redis
.zadd(
"active-calls",
format!("{}:{}", call.id, channel.id),
timestamp,
)
.await?;
redis
.zadd(
"active-calls",
format!("{}:{}", call.id, call.other_party_channel_id(channel.id)),
timestamp,
)
.await?;
} else {
ctx.send()
.content("☎️ Searching for a call...")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.content(format!(
"**TIP:** {}\n☎️ {}",
get_string_tips(ctx.prefix),
get_string_call_searching(ctx.prefix)
))
.await?;
}
Ok(())
@@ -121,7 +157,7 @@ impl Command<State> for CallCommand {
pub struct SkipCommand;
#[async_trait]
impl Command<State> for SkipCommand {
impl Command<State, Extras> for SkipCommand {
fn name(&self) -> &'static str {
"skip"
}
@@ -130,13 +166,17 @@ impl Command<State> for SkipCommand {
&["s", "next"]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State> + Send + Sync + 'static>> {
vec![Box::new(NotBannedPermission)]
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![
Box::new(NonNewAccountPermission),
Box::new(NotBannedPermission),
Box::new(IsCallParticipantPermission),
]
}
async fn execute(
&self,
ctx: CommandContext<'_, State>,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
let channel = Channel::get_or_create_by_id(
@@ -147,8 +187,7 @@ impl Command<State> for SkipCommand {
.await
.inspect_err(|e| {
log::error!("Failed to get or create channel: {e:?}");
})
.map_err(|_| CommandError::DatabaseQueryFailed)?;
})?;
if channel.call_id.is_none() {
ctx.send()
@@ -156,8 +195,7 @@ impl Command<State> for SkipCommand {
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -168,55 +206,94 @@ impl Command<State> for SkipCommand {
"☎️ You're already searching for a call! Use `{}hangup` to cancel the search.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
let call = Call::get_by_id(channel.call_id.unwrap(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
.ok_or(CommandError::DatabaseInconsistentState)?;
call.hangup(&ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?;
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
let other_channel_id = call.other_party_channel_id(ctx.event.channel_id.get());
ctx.rt
.http
.create_message(Id::new(other_channel_id))
.content("☎️ The other party hung up the phone.")
.content(&format!(
"☎️ {}",
get_string_call_hangup_other_party(ctx.prefix)
))
.await
.inspect_err(|e| {
log::error!("Failed to send message to other party: {e:?}");
})
.map_err(|_| CommandError::MessageSendingFailed)?;
})?;
let mut redis = ctx.rt.state.redis.get().await?;
let channel_keys = [
format!("{}:{}", call.id, call.channel_ids[0]),
format!("{}:{}", call.id, call.channel_ids[1]),
];
redis
.zrem("active-calls", &channel_keys)
.await
.inspect_err(|e| log::error!("Failed to remove inactive call from redis: {e}"))
.ok();
let call = Call::start(&channel, &ctx.rt.state.db)
.await
.inspect_err(|e| {
log::error!("Failed to start (skipped) call: {e:?}");
})
.map_err(|_| CommandError::DatabaseQueryFailed)?;
})?;
if let Some(call) = call {
ctx.send().content("☎️ Call connected. Say hi!").await.bye();
ctx.send()
.content(format!(
"**TIP:** {}\n☎️ Skipped! Searching for a call...\n☎️ {}",
get_string_tips(ctx.prefix),
get_string_call_answered(ctx.prefix)
))
.await
.bye();
ctx.rt
.http
.create_message(Id::new(call.other_party_channel_id(channel.id)))
.content("☎️ Call connected. Say hi!")
.content(&format!("☎️ {}", get_string_call_answered(ctx.prefix)))
.await
.bye();
let mut redis = ctx.rt.state.redis.get().await?;
let timestamp = UtcDateTime::now().unix_timestamp();
redis
.zadd(
"active-calls",
format!("{}:{}", call.id, channel.id),
timestamp,
)
.await?;
redis
.zadd(
"active-calls",
format!("{}:{}", call.id, call.other_party_channel_id(channel.id)),
timestamp,
)
.await?;
} else {
ctx.send()
.content("☎️ Skipped! Searching for a call...")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.content(format!(
"**TIP:** {}\n☎️ Skipped! Searching for a call...",
get_string_tips(ctx.prefix)
))
.await?;
}
Ok(())
@@ -227,7 +304,7 @@ impl Command<State> for SkipCommand {
pub struct HangupCommand;
#[async_trait]
impl Command<State> for HangupCommand {
impl Command<State, Extras> for HangupCommand {
fn name(&self) -> &'static str {
"hangup"
}
@@ -236,27 +313,29 @@ impl Command<State> for HangupCommand {
&["h", "hang"]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State> + Send + Sync + 'static>> {
vec![Box::new(NotBannedPermission)]
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![
Box::new(NonNewAccountPermission),
Box::new(NotBannedPermission),
Box::new(IsCallParticipantPermission),
]
}
async fn execute(
&self,
ctx: CommandContext<'_, State>,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
let Some(channel) = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
let Some(mut channel) = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))?
else {
ctx.send()
.content(format!(
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
};
@@ -267,52 +346,73 @@ impl Command<State> for HangupCommand {
.await
.inspect_err(|e| {
log::error!("Failed to cancel search: {e:?}");
})
.map_err(|_| CommandError::DatabaseQueryFailed)?;
})?;
ctx.send()
.content("☎️ The phone was hung up.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.content(format!("☎️ {}", get_string_call_no_answer(ctx.prefix)))
.await?;
return Ok(());
}
if let Some(call_id) = channel.call_id {
let mut redis = ctx.rt.state.redis.get().await?;
let Some(call) = Call::get_by_id(call_id, &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
else {
ctx.send()
.content("❌ Call not found.")
ctx.send().content("❌ The call could not be found.\n-# This is not supposed to happen. If the issue persists, contact a moderator in the official server.").await?;
channel.call_id = None;
channel.upsert(&ctx.rt.state.db).await.bye();
redis
.zrem("active-calls", format!("{}:{}", call_id, channel.id))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.bye();
return Err(CommandError::DatabaseInconsistentState);
};
let channel_keys = [
format!("{call_id}:{}", call.channel_ids[0]),
format!("{call_id}:{}", call.channel_ids[1]),
];
redis
.zrem("active-calls", &channel_keys)
.await
.inspect_err(|e| log::error!("Failed to remove inactive call from redis: {e}"))
.ok();
call.hangup(&ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?;
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
ctx.send().content("☎️ You hung up the phone.").await.bye();
ctx.send()
.content(format!(
"☎️ {}",
get_string_call_hangup_this_party(ctx.prefix)
))
.await
.bye();
ctx.rt
.http
.create_message(Id::new(call.other_party_channel_id(channel.id)))
.content("☎️ The other party hung up the phone.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.content(&format!(
"☎️ {}",
get_string_call_hangup_other_party(ctx.prefix)
))
.await?;
} else {
ctx.send()
.content(format!(
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
}
@@ -325,7 +425,7 @@ impl Command<State> for HangupCommand {
pub struct FriendRequestCommand;
#[async_trait]
impl Command<State> for FriendRequestCommand {
impl Command<State, Extras> for FriendRequestCommand {
fn name(&self) -> &'static str {
"friendreq"
}
@@ -338,19 +438,22 @@ impl Command<State> for FriendRequestCommand {
"Shows your username to the other party and asks them to send you a friend request on Discord."
}
fn permissions(&self) -> Vec<Box<dyn Permission<State> + Send + Sync + 'static>> {
vec![Box::new(NotBannedPermission)]
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![
Box::new(NonNewAccountPermission),
Box::new(NotBannedPermission),
Box::new(IsCallParticipantPermission),
]
}
async fn execute(
&self,
ctx: CommandContext<'_, State>,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
let channel = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?;
.inspect_err(|e| log::error!("Failed to get channel: {e:?}"))?;
let Some(channel) = channel else {
ctx.send()
@@ -358,8 +461,7 @@ impl Command<State> for FriendRequestCommand {
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
};
@@ -367,16 +469,14 @@ impl Command<State> for FriendRequestCommand {
let call = if let Some(call_id) = channel.call_id {
Call::get_by_id(call_id, &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
} else {
ctx.send()
.content(format!(
"❌ You're not on a call! Use `{}call` to start one.",
ctx.prefix
))
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Ok(());
};
@@ -384,15 +484,27 @@ impl Command<State> for FriendRequestCommand {
let Some(call) = call else {
ctx.send()
.content("❌ Oops! We could not find that call.")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
return Err(CommandError::DatabaseInconsistentState);
};
let other_channel_id = call.other_party_channel_id(channel.id);
let profile = get_display_profile(ctx.event);
let Some(participant) = Participant::get_for_user_and_channel_in_call(
ctx.event.author.id.get(),
ctx.event.channel_id.get(),
call.id,
&ctx.rt.state.db,
)
.await?
else {
ctx.send()
.content("❌ You haven't even said hi! Who are you trying to add?")
.await?;
return Ok(());
};
ctx
.rt
@@ -403,17 +515,113 @@ impl Command<State> for FriendRequestCommand {
.content(
&format!(
"📬 **{}** wants you to send them a friend request on Discord! Their username is `{}`.",
profile.name.sanitize(false),
participant.display_name().sanitize(false),
ctx.event.author.name.sanitize(false)
)
)
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
?;
ctx.send()
.content("📬 Asked the other party to send you a friend request!")
.await
.map_err(|_| CommandError::MessageSendingFailed)?;
.await?;
Ok(())
}
}
#[derive(Debug)]
pub struct MaskCommand;
#[async_trait]
impl Command<State, Extras> for MaskCommand {
fn name(&self) -> &'static str {
"mask"
}
fn aliases(&self) -> &'static [&'static str] {
&["m"]
}
fn description(&self) -> &'static str {
"Hides your profile from the other party by replacing your profile with a random animal. This command's preferences persist across calls.\n\nNote: Using this command without `on/off` will display your current mask status, without making any changes to it."
}
fn arguments(&self) -> &'static [Argument] {
&[Argument {
name: "on/off",
is_optional: true,
is_greedy: false,
}]
}
async fn execute(
&self,
mut ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let Arg(toggle) = match Arg::<Option<bool>>::parse(args, &ctx).await {
Ok(v) => v,
Err(_) => {
ctx.send()
.content(format!(
"❓ Are you sure that's correct? Use `{}mask on` and `{}mask off`, or just `{}mask` to toggle it.",
ctx.prefix, ctx.prefix, ctx.prefix
))
.await?;
return Ok(());
}
};
let mask_verb: &'static str;
// If toggle is Some, update user mask preference
if let Some(toggle) = toggle {
ctx.extras.user.is_masked = toggle;
ctx.extras.user.insert(&ctx.rt.state.db).await?;
mask_verb = "was";
} else {
mask_verb = "is";
}
let mask_status = if ctx.extras.user.is_masked {
"on"
} else {
"off"
};
let channel = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db).await?;
let mut mask_message = format!(
"🎭 Your mask {mask_verb} set to `{}`. You can toggle your mask on or off using `{}mask on` and `{}mask off`.",
mask_status, ctx.prefix, ctx.prefix
);
if let Some(channel) = channel
&& let Some(call_id) = channel.call_id
&& let Some(mut participant) = Participant::get_for_user_and_channel_in_call(
ctx.extras.user.id,
ctx.event.channel_id.get(),
call_id,
&ctx.rt.state.db,
)
.await?
{
participant.is_masked = ctx.extras.user.is_masked;
participant.upsert(&ctx.rt.state.db).await?;
if ctx.extras.user.is_masked {
mask_message = format!(
"🎭 Your mask {mask_verb} set to `on`. You're currently being displayed as **{} {}**. You can toggle your mask on or off using `{}mask on` and `{}mask off`.",
get_mask_emoji(&participant.user_mask).expect("User's mask did not exist"),
get_mask_display_name(&participant.user_mask),
ctx.prefix,
ctx.prefix
);
}
}
ctx.send().content(mask_message).await?;
Ok(())
}
+13 -11
View File
@@ -1,27 +1,29 @@
use crate::{framework::interactions::components::Button, state::State};
use crate::extras::Extras;
use crate::framework::interactions::components::Button;
use crate::state::State;
#[derive(Debug)]
pub struct CodeOfConductButton;
impl Button<State> for CodeOfConductButton {
fn label(&self) -> Option<&'static str> {
Some("Code of Conduct")
impl Button<State, Extras> for CodeOfConductButton {
fn label(&self) -> Option<String> {
Some("Code of Conduct".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://payphone.lat/code-of-conduct")
fn url(&self) -> Option<String> {
Some("https://payphone.lat/code-of-conduct".into())
}
}
#[derive(Debug)]
pub struct NeedHelpButton;
impl Button<State> for NeedHelpButton {
fn label(&self) -> Option<&'static str> {
Some("Need Help?")
impl Button<State, Extras> for NeedHelpButton {
fn label(&self) -> Option<String> {
Some("Need Help?".into())
}
fn url(&self) -> Option<&'static str> {
Some("https://discord.gg/9daSsrfTmE")
fn url(&self) -> Option<String> {
Some("https://discord.gg/9daSsrfTmE".into())
}
}
+15 -8
View File
@@ -1,17 +1,16 @@
use std::sync::Arc;
use twilight_model::{channel::message::Embed, oauth::Application};
use twilight_model::channel::message::Embed;
use twilight_model::oauth::Application;
use twilight_util::builder::embed::{
EmbedAuthorBuilder, EmbedBuilder, EmbedFieldBuilder, EmbedFooterBuilder, ImageSource,
};
use crate::{
constants::{COLOR_RED, COLOR_YELLOW},
database::models::Message,
discord::images,
groups::calls::moderation::Rule,
utils::ellipse,
};
use crate::constants::{COLOR_RED, COLOR_YELLOW};
use crate::database::models::Message;
use crate::discord::images;
use crate::groups::calls::moderation::Rule;
use crate::utils::ellipse;
pub fn first_warning_embed(
app: &Application,
@@ -27,6 +26,7 @@ pub fn first_warning_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
)
).unwrap()
)
@@ -49,6 +49,7 @@ pub fn first_warning_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap()
)
@@ -70,6 +71,7 @@ pub fn repeat_warning_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
)
).unwrap()
)
@@ -92,6 +94,7 @@ pub fn repeat_warning_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap()
)
@@ -113,6 +116,7 @@ pub fn first_ban_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
)
).unwrap()
)
@@ -135,6 +139,7 @@ pub fn first_ban_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
))
.unwrap()
)
@@ -156,6 +161,7 @@ pub fn final_ban_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
)
).unwrap()
)
@@ -178,6 +184,7 @@ pub fn final_ban_embed(
app.icon,
app.bot.as_ref().unwrap().id.get(),
app.bot.as_ref().unwrap().discriminator as u64,
None
)
).unwrap()
)
+301 -84
View File
@@ -1,38 +1,42 @@
use std::{error::Error, sync::Arc};
use std::error::Error;
use std::sync::Arc;
use async_trait::async_trait;
use deadpool_redis::redis::AsyncTypedCommands;
use itertools::Itertools;
use twilight_model::{
gateway::payload::incoming::{MessageCreate, MessageDelete, MessageUpdate},
id::Id,
use time::{Duration, UtcDateTime};
use twilight_http::api_error::ApiError;
use twilight_http::error::ErrorType;
use twilight_model::gateway::payload::incoming::{MessageCreate, MessageDelete, MessageUpdate};
use twilight_model::id::Id;
use twilight_util::builder::embed::{
EmbedAuthorBuilder, EmbedBuilder, EmbedFooterBuilder, ImageSource,
};
use twilight_util::builder::embed::{EmbedAuthorBuilder, EmbedBuilder, ImageSource};
use twilight_util::snowflake::Snowflake;
use crate::{
constants::COLOR_WHITE,
database::models::{Call, Channel, Message, User, UserIncident},
discord::sanitizing::SanitizeDiscordMarkdown,
framework::{
events::traits::{
EventResult, OnMessageDeleteHandler, OnMessageEditHandler, OnMessageHandler,
},
interactions::components::ActionRow,
runtime::Runtime,
},
groups::calls::{
components::{CodeOfConductButton, NeedHelpButton},
embeds, get_display_profile,
moderation::{Action, Rule, escape_message},
},
state::State,
utils::{ellipse, i64_to_u64},
use crate::constants::{COLOR_WHITE, COLOR_YELLOW};
use crate::database::models::{Call, Channel, Message, Participant, User, UserIncident};
use crate::discord::images;
use crate::discord::sanitizing::SanitizeDiscordMarkdown;
use crate::extras::Extras;
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::events::traits::{
EventResult, OnMessageDeleteHandler, OnMessageEditHandler, OnMessageHandler,
};
use crate::framework::interactions::components::ActionRow;
use crate::framework::runtime::Runtime;
use crate::groups::calls::components::{CodeOfConductButton, NeedHelpButton};
use crate::groups::calls::masks::{get_mask_avatar_url, get_mask_display_name};
use crate::groups::calls::moderation::{Action, Rule, escape_message, moderate_message};
use crate::groups::calls::{embeds, moderation};
use crate::state::State;
use crate::utils::{ellipse, i64_to_u64};
async fn penalize_user(
user: User,
message: Message,
broken_rules: Vec<Arc<dyn Rule>>,
rt: &Runtime<State>,
rt: &Runtime<State, Extras>,
) -> Result<(), Box<dyn Error>> {
let reason = format!(
"You broke the following rules during a call:\n{}",
@@ -46,7 +50,7 @@ async fn penalize_user(
.incident(
reason.clone(),
Some(message.data.clone()),
Some(user.id),
None,
&rt.state.db,
)
.await?;
@@ -85,12 +89,32 @@ async fn penalize_user(
pub struct CallMessageHandler;
#[async_trait]
impl OnMessageHandler<State> for CallMessageHandler {
async fn on_message(&self, event: &MessageCreate, rt: Arc<Runtime<State>>) -> EventResult {
impl OnMessageHandler<State, Extras> for CallMessageHandler {
async fn on_message(
&self,
event: &MessageCreate,
rt: Arc<Runtime<State, Extras>>,
_extras: Arc<dyn ExtrasGetter<State, Extras = Extras>>,
) -> EventResult {
if event.author.bot || event.author.system.unwrap_or(false) {
return Ok(());
}
if UtcDateTime::from_unix_timestamp(event.author.id.timestamp() / 1000).unwrap()
> UtcDateTime::now() - Duration::days(30)
&& event.author.id.get() != rt.state.bot_owner_id
{
return Ok(());
}
if event.content.is_empty() {
return Ok(());
}
let Some(guild_id) = event.guild_id else {
return Ok(());
};
let prefixes = rt
.get_prefixes(event.guild_id.map(|i| i.get()), Some(event.author.id.get()))
.await;
@@ -141,6 +165,13 @@ impl OnMessageHandler<State> for CallMessageHandler {
return Ok(());
};
let mut user = User::create_or_update(
event.author.clone(),
&rt.state.db,
&rt.state.color_queue_sender,
)
.await?;
let user_incidents = UserIncident::get_for_user(event.author.id.get(), &rt.state.db)
.await?
.iter()
@@ -151,7 +182,27 @@ impl OnMessageHandler<State> for CallMessageHandler {
return Ok(());
}
let Some(opposite_channel) = Channel::get_by_id(
if event.content.to_ascii_lowercase().starts_with("x ") {
if !user.findings.contains("feature:hide-message") {
user.findings.insert("feature:hide-message".into());
user.insert(&rt.state.db).await?;
rt
.http
.create_message(
event.channel_id
)
.content(
"✨ You found a hidden feature! Messages starting with `x` followed by a space will not be sent to the other party (nor moderated, i.e. you won't get banned for what you say in them)."
)
.reply(event.id)
.await?;
}
return Ok(());
}
let Some(mut opposite_channel) = Channel::get_by_id(
call.other_party_channel_id(event.channel_id.get()),
&rt.state.db,
)
@@ -165,17 +216,28 @@ impl OnMessageHandler<State> for CallMessageHandler {
return Ok(());
};
if opposite_channel.call_id != Some(call.id) {
log::error!(
"Channel {} is listed as the opposite channel of channel {} in call {}, but its call ID is {}.",
opposite_channel.id,
channel.id,
call.id,
opposite_channel
.call_id
.map_or("None".into(), |i| i.to_string())
);
return Ok(());
}
let Some((webhook_id, webhook_token)) = opposite_channel
.webhook_id
.zip(opposite_channel.webhook_token)
.zip(opposite_channel.webhook_token.clone())
else {
// Handle DM calls in the future.
return Ok(());
};
let profile = get_display_profile(event);
let (content, rules) = escape_message(event);
let (content, rules) = escape_message(event, user.is_moderator);
let message: Message;
@@ -195,29 +257,59 @@ impl OnMessageHandler<State> for CallMessageHandler {
};
let replying_to_id = replying_to.as_ref().map(|i| i.message_id);
let participant = Participant::get_or_create(
user.id,
event.channel_id.get(),
call.id,
event
.member
.clone()
.and_then(|member| member.nick)
.or(event.author.global_name.clone())
.unwrap_or(event.author.name.clone()),
images::get_avatar_url(
event
.member
.clone()
.and_then(|inner| inner.avatar)
.or(event.author.avatar),
event.author.id.get(),
event.author.discriminator as u64,
event
.member
.as_ref()
.and_then(|member| member.avatar)
.map(|_| guild_id.get()),
),
user.is_masked,
&rt.state.db,
)
.await?;
if rules
.iter()
.filter(|rule| !rule.ignore_for_moderators() || !user.is_moderator)
.any(|rule| rule.action() == &Action::BlockAndPenalty)
{
rt.http
.create_message(event.channel_id)
.content(
"❌ Your message has been blocked because it broke Payphone's code of conduct. Check your DMs for more information.",
"🚩 Your message has been blocked because it broke Payphone's code of conduct. Check your DMs for more information.",
)
.await?;
rt.http
.create_message(Id::new(opposite_channel.id))
.content(&format!(
"❌ **{}** Sent a message that was blocked.\n-# If you see an inappropiate message, please report it using `Message > Apps > Report Message`.",
profile.name.sanitize(false)
"🚩 **{}** Sent a message that was blocked.\n-# If you see an inappropiate message, please report it using `Message > Apps > Report Message`.",
participant.display_name().sanitize(false)
))
.await?;
message = Message::build()
.call_id(call.id)
.message(event.0.clone())
.profile(profile.clone())
.participant(participant)
.is_censored(!rules.is_empty())
.replying_to_message_id(replying_to_id)
.build()
@@ -227,26 +319,130 @@ impl OnMessageHandler<State> for CallMessageHandler {
} else {
let mut embeds = vec![];
if let Some(replying_to) = replying_to {
if let Some(replying_to) = replying_to
&& let Some((propagation_channel_id, propagation_message_id)) = replying_to
.data
.propagation_channel_id
.zip(replying_to.data.propagation_message_id)
{
let (display_name, avatar_url) = if let Some(mask) = &replying_to.data.author_mask {
(
if i64_to_u64(propagation_channel_id) != event.channel_id.get() {
get_mask_display_name(mask)
} else {
format!(
"{} ({})",
get_mask_display_name(mask),
moderation::moderate_message(&replying_to.data.author_name, false)
.0
)
},
get_mask_avatar_url(mask).expect("Failed to get mask avatar URL"),
)
} else {
(
moderation::moderate_message(&replying_to.data.author_name, false).0,
replying_to.data.author_avatar_url.clone(),
)
};
// Replied-to links are always
// .../{other_party_server_id}/{other_party_channel_id}/{other_party_message_id}
//
// When the message being replied to was sent by the other party, the
// `other_party_message_id` is the original message ID, given it was sent from
// their channel so the original is in their channel.
//
// When the message being replied to was sent by this party, the
// `other_party_message_id` is the propagation message ID given the other party
// will have seen the propagated message instead.
let message_link = if i64_to_u64(propagation_channel_id) == channel.id {
// if the message replied-to was sent by the other party
//
// replied_to.message_id -> other party's channel id
// replied_to.propagation_channel_id -> this channel's ID
// replied_to.propagation_message_id -> this channel's message ID
format!(
"https://discord.com/channels/{}/{}/{}",
opposite_channel.server_id, opposite_channel.id, replying_to.message_id
)
} else {
// if the message replied-to was sent by this party
//
// replied_to.message_id -> this channel's message ID
// replied_to.propagation_channel_id -> other party's channel id
// replied_to.propagation_message_id -> other party's message ID
format!(
"https://discord.com/channels/{}/{}/{}",
opposite_channel.server_id, propagation_channel_id, propagation_message_id
)
};
let replying_to_user = User::get_by_id(replying_to.author_id, &rt.state.db).await?;
embeds.push(
EmbedBuilder::new()
.author(
EmbedAuthorBuilder::new(replying_to.data.author_name).icon_url(
ImageSource::url(replying_to.data.author_avatar_url).unwrap(),
),
EmbedAuthorBuilder::new(format!("Replying to {display_name}",))
.icon_url(ImageSource::url(avatar_url).unwrap())
.url(message_link),
)
.color(COLOR_WHITE)
.description(ellipse(replying_to.data.content, 100))
.color(if replying_to.data.author_mask.is_some() {
COLOR_WHITE
} else {
replying_to_user
.and_then(|i| i.color.map(|c| c as u32))
.unwrap_or(COLOR_WHITE)
})
.description(ellipse(
moderate_message(&replying_to.data.content, false).0,
100,
))
.build(),
);
}
let message_sent = rt
if participant.is_masked {
let last_message =
Message::get_last_by_author_id(call.id, event.author.id.get(), &rt.state.db)
.await?;
if last_message
.map(|lm| lm.data.author_mask.is_none())
.unwrap_or(true)
{
embeds.push(
EmbedBuilder::new()
.color(COLOR_YELLOW)
.description(format!(
"🎭 **{}** is wearing a mask! Their real identity is hidden.",
participant.display_name()
))
.footer(EmbedFooterBuilder::new(format!(
"You can set your own mask using {}mask on.",
prefixes[0]
)))
.build(),
);
}
}
let mut redis = rt.state.redis.get().await?;
redis
.zadd(
"active-calls",
format!("{}:{}", call.id, channel.id),
UtcDateTime::now().unix_timestamp(),
)
.await?;
let message_sent = match rt
.http
.execute_webhook(Id::new(webhook_id), &webhook_token)
.allowed_mentions(None)
.username(&profile.name)
.avatar_url(&profile.avatar_url)
.username(&moderation::moderate_message(&participant.display_name(), false).0)
.avatar_url(&participant.avatar_url())
.content(&content.sanitize_mentions())
.embeds(&embeds)
.wait()
@@ -257,14 +453,30 @@ impl OnMessageHandler<State> for CallMessageHandler {
call.id,
opposite_channel.id
);
})?
.model()
.await?;
}) {
Ok(message) => message,
Err(e) => {
if let ErrorType::Response {
error: ApiError::General(error),
..
} = e.kind()
&& error.code == 10015
{
log::debug!("Webhook not found, updating...");
opposite_channel
.update_webhook(&rt.state.db, &rt.http)
.await?;
}
return Ok(());
}
}
.model()
.await?;
message = Message::build()
.call_id(call.id)
.message(event.0.clone())
.profile(profile.clone())
.participant(participant)
.is_censored(!rules.is_empty())
.replying_to_message_id(replying_to_id)
.propagation_message_id(message_sent.id.get())
@@ -281,18 +493,6 @@ impl OnMessageHandler<State> for CallMessageHandler {
.iter()
.any(|rule| rule.action() == &Action::BlockAndPenalty)
{
let user = User::get_by_id(event.author.id.get(), &rt.state.db).await?;
let user = if let Some(user) = user {
user
} else {
let user: User = event.author.clone().into();
user.insert(&rt.state.db).await?;
user
};
penalize_user(user, message, rules, &rt).await?;
}
@@ -304,8 +504,23 @@ impl OnMessageHandler<State> for CallMessageHandler {
pub struct CallMessageEditHandler;
#[async_trait]
impl OnMessageEditHandler<State> for CallMessageEditHandler {
async fn on_message_edit(&self, event: &MessageUpdate, rt: Arc<Runtime<State>>) -> EventResult {
impl OnMessageEditHandler<State, Extras> for CallMessageEditHandler {
async fn on_message_edit(
&self,
event: &MessageUpdate,
rt: Arc<Runtime<State, Extras>>,
) -> EventResult {
if event.edited_timestamp.is_none() {
return Ok(());
}
log::trace!(
"Edited message was '{}' sent by {} (bot? {:?})",
event.content,
event.author.id.get(),
event.author.bot
);
let Some(channel) = Channel::get_by_id(event.channel_id.get(), &rt.state.db).await? else {
return Ok(());
};
@@ -337,7 +552,7 @@ impl OnMessageEditHandler<State> for CallMessageEditHandler {
};
if let Some(propagation_message_id) = message.data.propagation_message_id {
let (content, rules) = escape_message(event);
let (content, rules) = escape_message(event, false);
if rules
.iter()
@@ -346,16 +561,19 @@ impl OnMessageEditHandler<State> for CallMessageEditHandler {
rt.http
.create_message(event.channel_id)
.content(
"❌ Your message's edit has been blocked because it broke Payphone's code of conduct. Check your DMs for more information.",
"🚩 Your message's edit has been blocked because it broke Payphone's code of conduct. Check your DMs for more information.",
)
.reply(event.id)
.await?;
let user = User::get_by_id(event.author.id.get(), &rt.state.db).await?;
let user = User::create_or_update(
event.author.clone(),
&rt.state.db,
&rt.state.color_queue_sender,
)
.await?;
if let Some(user) = user {
penalize_user(user, message, rules, &rt).await?;
}
penalize_user(user, message, rules, &rt).await?;
return Ok(());
}
@@ -389,11 +607,11 @@ impl OnMessageEditHandler<State> for CallMessageEditHandler {
pub struct CallMessageDeleteHandler;
#[async_trait]
impl OnMessageDeleteHandler<State> for CallMessageDeleteHandler {
impl OnMessageDeleteHandler<State, Extras> for CallMessageDeleteHandler {
async fn on_message_delete(
&self,
event: &MessageDelete,
rt: Arc<Runtime<State>>,
rt: Arc<Runtime<State, Extras>>,
) -> EventResult {
let Some(channel) = Channel::get_by_id(event.channel_id.get(), &rt.state.db).await? else {
return Ok(());
@@ -425,23 +643,22 @@ impl OnMessageDeleteHandler<State> for CallMessageDeleteHandler {
return Ok(());
};
if let Some(propagation_message_id) = message.data.propagation_message_id {
if let Some((webhook_id, webhook_token)) = opposite_channel
if let Some(propagation_message_id) = message.data.propagation_message_id
&& let Some((webhook_id, webhook_token)) = opposite_channel
.webhook_id
.zip(opposite_channel.webhook_token)
{
rt.http
.delete_webhook_message(
Id::new(webhook_id),
&webhook_token,
Id::new(i64_to_u64(propagation_message_id)),
)
.await?;
{
rt.http
.delete_webhook_message(
Id::new(webhook_id),
&webhook_token,
Id::new(i64_to_u64(propagation_message_id)),
)
.await?;
message.data.is_deleted = true;
message.data.is_deleted = true;
message.insert(&rt.state.db).await?;
}
message.insert(&rt.state.db).await?;
}
Ok(())
@@ -1,6 +1,15 @@
scum
idiot
stupid
dumb
moron
fool
fool
stfu
syfm
sybau
gtfo
// Keys is only censored because there have been many genuine conversations about piano keys, keys,
// and other stuff.
keys
// Many people not knowing paki is a slur, it's better to keep it here.
paki
hoe
ho
@@ -1,5 +1,7 @@
sex
segs
esex
esegs
give head
gave head
give me head
@@ -35,7 +37,11 @@ stick it in yr pussy
cock
dick
dih
pussy
pusy
posay
vagina
vgina
vgna
dck
psy
pu-c
@@ -50,27 +56,32 @@ gang bang
squirt
squirting
squirts
bitch
bih
bich
ho
hoe
huz
slut
dldo
dildo
goon
goon / go on
gooning
i will fuh you
i will fuck you
i will fuh u
i will fuh you
i will fuck u
i will fuck you
i will fvck u
i will fvck you
i will fck u
i will fck you
nut
nuting
goonbeam
goonbeaming
gooncream
gooncreaming
goonbud
goonbuds
goonete
goonetes
gooner
goonr
goner
boty hole
suck my pp
ass cracker
@@ -86,11 +97,43 @@ masturbate
masturbating
masterbating
masterbaiting
masturbatigng
masterbaiter
mastrbaiter
mastrbait
mastrbate
horny
hrny
whore
whore / who re
whre
tickle your pickle
tickle yr pickle
tickle his pickle
tickle my pickle
tickle my pickle
peg
peged
peging
butbang
butbanged
eat my ass
eat my ahh
eat mi ass
eat my ahh
eat my bum
eat mi bum
ima touch you
ima touch u
i ma touch you
i ma touch u
il touch you
il touch u
im going to touch you
im going to touch u
im gonna touch you
im gonna touch u
nude
nudes
nde
ndes
nood
noods
@@ -1,49 +1,53 @@
niga
nigas
niger
nigers
nig
nigs
nga
ngas
ngr
ngrs
nger
ngers
qiga
qigas
niqa
niqas
niqer
niqers
nqa
nqas
nqer
nlga
nlger
digga
nlgers
ngiga
ngigas
negaras
nigy
nyga
diga
digas
fag
fags
fagot
fagots
fgot
fgots
fgt
paki
fgts
phagot
phagots
retard
retards
rtrd
rtrds
tard
dumbfuck
dumbfck
dumbfuk
dumbfuh
dumbfuhk
dmbfuck
dmbfck
dmbfuk
dmbfuh
dmbfuhk
dumb fuck
dumb fck
dumb fuk
dumb fuh
dumb fuhk
stfu
shut the fuck up
syfm
shut your fucking mouth
sybau
shut your bitch as up
shut your bih as up
gtfo
get the fuck out
pedo
pdf
pdfile
tards
blackie
blackies
motherfucker
mf
motherfuckers
chinese ape
chinese apes
+5 -3
View File
@@ -9,8 +9,10 @@ fuck you
f u
f you
fuck u
damn
dmn
shit
sht
ass
ass
huz
bitch
bih
bich
@@ -1 +1,3 @@
lkrkfejnkjrngkjngrkjgenkgejnrkjgnknj
pedo
pdf
pdfile
@@ -5,13 +5,9 @@ hang urself
hang yourself
gkys
gokys
keys
get raped
rape you
rape u
slit
grape
graped
throat slit
slit your throat
slit ur throat
+7
View File
@@ -0,0 +1,7 @@
{
"dinosaur": 1278255435652010014,
"shleepy cat": 1278255475066146816,
"cozy cat": 1278255420124696663,
"coquette cat": 1278255408254816300,
"panic cat": 1278255451993145345
}
+52
View File
@@ -0,0 +1,52 @@
{
"ferret": 1278176917123760139,
"octopus": 1278176904410697880,
"cat": 1278176891290783824,
"monkey": 1278176881195094049,
"panda": 1278176868767629455,
"sheep": 1278176856910073946,
"horse": 1278176842116894760,
"bee": 1278176823846506577,
"wild boar": 1278176806498996235,
"duck": 1278176794591232102,
"chicken": 1278176781790216233,
"elephant": 1278176771413512213,
"cow": 1278176761565413483,
"deer": 1278176744691597312,
"turkey": 1278176730619576321,
"dog": 1278176719932751903,
"beaver": 1278176709530882091,
"camel": 1278176699921465394,
"koala": 1278176687493746709,
"hippo": 1278176675846295603,
"ostrich": 1278176661317095494,
"rhino": 1278176650340864000,
"squirrel": 1278176637627924570,
"chamaleon": 1278176625392877648,
"frog": 1278176614512857088,
"skunk": 1278176604509442079,
"walrus": 1278176554723311678,
"hedgehog": 1278176541750067252,
"pig": 1278176531415564332,
"hen": 1278176518643646485,
"turtle": 1278176507428343891,
"mouse": 1278175957047578696,
"rabbit": 1278175944007487489,
"goat": 1278175933915856938,
"lion": 1278175922964664382,
"wolf": 1278175902047535165,
"snake": 1278175869331968061,
"llama": 1278175850008674325,
"crab": 1278175835634925620,
"owl": 1278175822947029152,
"bat": 1278175813572886550,
"zebra": 1278175799962505216,
"fox": 1278175788818104474,
"gorilla": 1278175775891259456,
"sloth": 1278175765661356175,
"puffer fish": 1278175753497743360,
"bear": 1278175741569142867,
"giraffe": 1278175732601983006,
"penguin": 1278175721956573236,
"parrot": 1278175706798489642
}
+53
View File
@@ -0,0 +1,53 @@
use std::collections::HashMap;
use once_cell::sync::Lazy;
use rand::{SeedableRng, seq::IndexedRandom};
use rand_chacha::ChaCha20Rng;
use crate::utils::ToTitleCase;
static MASKS_COMMON: Lazy<HashMap<String, u64>> = Lazy::new(|| {
let (file_name, json) = if cfg!(debug_assertions) {
("dev/common.json", include_str!("dev/common.json"))
} else {
("prod/common.json", include_str!("prod/common.json"))
};
let masks: HashMap<String, u64> = serde_json::from_str(json)
.unwrap_or_else(|_| panic!("Failed to parse masks/{file_name} masks"));
assert_ne!(masks.len(), 0, "No masks found in masks/{file_name}");
masks
});
pub fn get_random_mask(not_in: &[String]) -> Option<(String, u64)> {
let mask_names = MASKS_COMMON
.iter()
.filter(|(name, _)| !not_in.contains(name))
.map(|(name, value)| (name.clone(), *value))
.collect::<Vec<_>>();
let mut rng = ChaCha20Rng::from_os_rng();
mask_names.choose(&mut rng).cloned()
}
pub fn get_mask_display_name(mask: impl ToString) -> String {
mask.to_title_case()
}
pub fn get_mask_emoji(mask: impl ToString) -> Option<String> {
let emoji_name = mask.to_string().replace(" ", "");
let emoji_id = MASKS_COMMON.get(&mask.to_string())?;
Some(format!("<:{emoji_name}:{emoji_id}>"))
}
pub fn get_mask_avatar_url(mask: impl ToString) -> Option<String> {
let mask_emoji_id = MASKS_COMMON.get(&mask.to_string())?;
Some(format!(
"https://cdn.discordapp.com/emojis/{mask_emoji_id}.png?size=128&quality=lossless"
))
}
+7
View File
@@ -0,0 +1,7 @@
{
"dinosaur": 1278254725833297965,
"shleepy cat": 1278254779767984181,
"cozy cat": 1278254704324771893,
"coquette cat": 1278254684200636428,
"panic cat": 1278254760700674098
}
+52
View File
@@ -0,0 +1,52 @@
{
"ferret": 1278173356423909448,
"octopus": 1278173331421397072,
"cat": 1278173317034934282,
"monkey": 1278173297456185344,
"panda": 1278173272390762538,
"sheep": 1278173251914432563,
"horse": 1278173237582237708,
"bee": 1278173216652787826,
"wild boar": 1278173196658413649,
"duck": 1278173181483679918,
"chicken": 1278173167218589726,
"elephant": 1278173150063886346,
"cow": 1278173125024153733,
"deer": 1278173110105014406,
"turkey": 1278173091796877363,
"dog": 1278173070846201856,
"beaver": 1278173051485425705,
"camel": 1278173035018584086,
"koala": 1278173021345021952,
"hippo": 1278173007419932804,
"ostrich": 1278172994669248523,
"rhino": 1278172980848885832,
"squirrel": 1278172965590274088,
"chamaleon": 1278172953305022496,
"frog": 1278172937043710094,
"skunk": 1278172923495976981,
"walrus": 1278172912368619603,
"hedgehog": 1278172899911405678,
"pig": 1278172885239861338,
"hen": 1278172871302184994,
"turtle": 1278172858199314455,
"mouse": 1278172846442414081,
"rabbit": 1278172831921999945,
"goat": 1278172815421472808,
"lion": 1278172803534684235,
"wolf": 1278172791052570687,
"snake": 1278172776259260547,
"llama": 1278172764913799168,
"crab": 1278172752322232330,
"owl": 1278172738309193749,
"bat": 1278172726426865724,
"zebra": 1278172715114565753,
"fox": 1278172702955274292,
"gorilla": 1278172687797194824,
"sloth": 1278172676837343242,
"puffer fish": 1278172665093558294,
"bear": 1278172653076746301,
"giraffe": 1278172640296702073,
"penguin": 1278172627629899808,
"parrot": 1278172600702337074
}
+3 -51
View File
@@ -1,59 +1,11 @@
//! Call commands and events.
use twilight_model::gateway::payload::incoming::MessageCreate;
use twilight_validate::request::webhook_username;
use crate::discord::images;
pub mod commands;
pub(super) mod components;
pub(super) mod embeds;
pub mod events;
pub mod masks;
pub(super) mod moderation;
pub(super) mod permissions;
#[derive(Debug, Clone)]
pub struct DisplayProfile {
pub id: u64,
pub name: String,
pub avatar_url: String,
pub mask: Option<String>,
}
fn get_display_profile(event: &MessageCreate) -> DisplayProfile {
let member = event.member.clone();
let name = if let Some(nick) = &member.clone().and_then(|member| member.nick) {
if webhook_username(nick).is_err() {
"Invalid Nickname".to_string()
} else {
nick.clone()
}
} else if let Some(name) = &event.author.global_name {
if webhook_username(name).is_err() {
"Invalid Global Name".to_string()
} else {
name.clone()
}
} else if webhook_username(&event.author.name).is_err() {
"Invalid Username".to_string()
} else {
event.author.name.clone()
};
let avatar_hash = member
.and_then(|inner| inner.avatar)
.or(event.author.avatar);
let avatar_url = images::get_avatar_url(
avatar_hash,
event.author.id.get(),
event.author.discriminator as u64,
);
DisplayProfile {
id: event.author.id.get(),
name,
avatar_url,
mask: None,
}
}
pub(super) mod strings;
pub mod tasks;
+154 -68
View File
@@ -83,8 +83,11 @@
//!
//! All of which would be detected.
use std::{collections::HashMap, sync::Arc};
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;
use itertools::Itertools;
use linkify::LinkFinder;
use once_cell::sync::Lazy;
use regex::Regex;
@@ -98,12 +101,13 @@ use crate::discord::sanitizing::SanitizeDiscordMarkdown;
/// and @here pings, and censoring by rules.
///
/// Arguments:
/// * `event`: The incoming message event to escape.
/// * `event` - The incoming message event to escape.
/// * `is_moderator` - Whether the message was sent by a moderator.
///
/// Returns:
/// [`(String, Vec<Arc<dyn Rule>>)`] - The escaped and censored message, and a vector of the rules
/// broken.
pub fn escape_message(event: &Message) -> (String, Vec<Arc<dyn Rule>>) {
pub fn escape_message(event: &Message, is_moderator: bool) -> (String, Vec<Arc<dyn Rule>>) {
let mut message = event.content.to_string();
for mention in &event.mentions {
@@ -124,9 +128,10 @@ pub fn escape_message(event: &Message) -> (String, Vec<Arc<dyn Rule>>) {
);
}
let (censored, rules) = moderate_message(&message);
let (censored, rules) = moderate_message(&message, is_moderator);
log::debug!("Escaped and normalized message: {censored:?}");
log::debug!("Rules broken: {rules:?}");
(censored, rules)
}
@@ -247,7 +252,7 @@ fn regex_from_phrase(phrase: &str) -> String {
///
/// Returns:
/// [`Regex`] - The merged regex for the phrases.
fn regex_from_phrases_list(phrases: &[&str]) -> Regex {
fn regex_from_phrases_list(phrases: &[String]) -> Regex {
let mut pattern = String::new();
for phrase in phrases {
@@ -270,15 +275,21 @@ type RuleAnalysis = ((Vec<String>, Vec<String>), Arc<dyn Rule>);
/// Arguments:
/// * `original` - The original message without normalization.
/// * `normalized` - The normalized version of the message.
/// * `is_moderator` - Whether the message was sent by a moderator.
///
/// Returns:
/// [`Vec<RuleAnalysis>`] - The results of the analysis, including all detections (on the original
/// message first, on the normalized message later) and their associated rules.
pub fn analyze_message(original: &str, normalized: &str) -> Vec<RuleAnalysis> {
pub fn analyze_message(original: &str, normalized: &str, is_moderator: bool) -> Vec<RuleAnalysis> {
let mut results = Vec::new();
for rule in RULES.iter() {
if rule.ignore_for_moderators() && is_moderator {
continue;
}
let (original_detections, normalized_detections) = rule.detect(original, normalized);
if !normalized_detections.is_empty() || !original_detections.is_empty() {
results.push(((original_detections, normalized_detections), rule.clone()));
}
@@ -348,13 +359,14 @@ pub fn censor_message(
///
/// Arguments:
/// * `original` - The original message.
/// * `is_moderator` - Whether the message was sent by a moderator.
///
/// Returns:
/// [`(String, Vec<Arc<dyn Rule>>)`] - The censored message and the rules that were broken.
pub fn moderate_message(original: &str) -> (String, Vec<Arc<dyn Rule>>) {
pub fn moderate_message(original: &str, is_moderator: bool) -> (String, Vec<Arc<dyn Rule>>) {
let normalized = normalize(original.to_string());
let analysis = analyze_message(original, &normalized.message);
let analysis = analyze_message(original, &normalized.message, is_moderator);
let censored = censor_message(original, normalized, &analysis);
(censored, analysis.iter().map(|(_, r)| r.clone()).collect())
@@ -376,7 +388,7 @@ pub enum Action {
/// Trait implemented by all rules.
#[allow(dead_code)]
pub trait Rule: Send + Sync {
pub trait Rule: Send + Sync + Debug {
/// The rule's human-readable name.
fn name(&self) -> &'static str;
@@ -397,6 +409,16 @@ pub trait Rule: Send + Sync {
/// [`(Vec<String>, Vec<String>)`] - The list of detected rule violations in the original
/// (first vector) and normalized (second vector) message.
fn detect(&self, original: &str, normalized: &str) -> (Vec<String>, Vec<String>);
/// Whether this rule should be ignored for moderators. This is used to avoid censoring
/// messages from moderators, while still allowing them to be detected and logged from regular
/// users.
///
/// Returns:
/// [`bool`] - Whether this rule should be ignored for moderators.
fn ignore_for_moderators(&self) -> bool {
false
}
}
/// Parses a file containing phrases to be detected by rules.
@@ -405,31 +427,64 @@ pub trait Rule: Send + Sync {
/// * `file_content` - The content of the file to parse.
///
/// Returns:
/// [`Vec<&str>`] - The list of phrases found in the file.
fn parse_phrases_file(file_content: &str) -> Vec<&str> {
file_content
.lines()
.filter_map(|line| {
let trimmed = line.trim();
if !trimmed.is_empty() && !trimmed.starts_with("//") {
Some(trimmed)
/// [`(Vec<String>, Vec<String>)`] - The list of phrases found in the file.
fn parse_phrases_file(file_content: &str) -> (Vec<String>, Vec<String>) {
let mut banned = vec![];
let mut exceptions = vec![];
for line in file_content.lines() {
let trimmed = line.trim().to_ascii_lowercase();
if !trimmed.is_empty() && !trimmed.starts_with("//") {
if let Some((phrase, phrase_exceptions)) = trimmed.split_once("/") {
banned.push(phrase.trim().to_string());
exceptions.extend(phrase_exceptions.split(',').map(|s| s.trim().to_string()));
} else {
banned.push(trimmed.to_string());
}
}
}
(banned, exceptions)
}
fn find_with_exceptions(message: &str, pattern: &Regex, exceptions: &[String]) -> Vec<String> {
pattern
.find_iter(message)
.filter_map(|m| {
let string = message[m.start()..m.end()].to_string();
if exceptions.contains(
&string
.split_ascii_whitespace()
.join(" ")
.to_ascii_lowercase(),
) {
None
} else {
Some(string)
}
})
.collect()
}
struct HateSpeechAndSlursRule(Regex);
#[derive(Debug)]
struct HateSpeechAndSlursRule {
pattern: Regex,
exceptions: Vec<String>,
}
impl HateSpeechAndSlursRule {
fn new() -> Self {
let phrases: Vec<&str> =
let (phrases, exceptions) =
parse_phrases_file(include_str!("lists/hate-speech-and-slurs.txt"));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -445,24 +500,28 @@ impl Rule for HateSpeechAndSlursRule {
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
struct ThreatsAndSelfHarmRule(Regex);
#[derive(Debug)]
struct ThreatsAndSelfHarmRule {
pattern: Regex,
exceptions: Vec<String>,
}
impl ThreatsAndSelfHarmRule {
fn new() -> Self {
let phrases: Vec<&str> =
let (phrases, exceptions) =
parse_phrases_file(include_str!("lists/threats-and-self-harm.txt"));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -478,24 +537,28 @@ impl Rule for ThreatsAndSelfHarmRule {
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
struct ExplicitSexualLanguageRule(Regex);
#[derive(Debug)]
struct ExplicitSexualLanguageRule {
pattern: Regex,
exceptions: Vec<String>,
}
impl ExplicitSexualLanguageRule {
fn new() -> Self {
let phrases: Vec<&str> =
let (phrases, exceptions) =
parse_phrases_file(include_str!("lists/explicit-sexual-language.txt"));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -511,23 +574,28 @@ impl Rule for ExplicitSexualLanguageRule {
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
struct SuggestiveLanguageRule(Regex);
#[derive(Debug)]
struct SuggestiveLanguageRule {
pattern: Regex,
exceptions: Vec<String>,
}
impl SuggestiveLanguageRule {
fn new() -> Self {
let phrases: Vec<&str> = parse_phrases_file(include_str!("lists/suggestive-language.txt"));
let (phrases, exceptions) =
parse_phrases_file(include_str!("lists/suggestive-language.txt"));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -543,14 +611,12 @@ impl Rule for SuggestiveLanguageRule {
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
#[derive(Debug)]
struct AdvertisingRule;
impl Rule for AdvertisingRule {
@@ -578,19 +644,30 @@ impl Rule for AdvertisingRule {
(detections, vec![])
}
fn ignore_for_moderators(&self) -> bool {
true
}
}
struct SensitiveTopicsAndTriggeringContentRule(Regex);
#[derive(Debug)]
struct SensitiveTopicsAndTriggeringContentRule {
pattern: Regex,
exceptions: Vec<String>,
}
impl SensitiveTopicsAndTriggeringContentRule {
fn new() -> Self {
let phrases: Vec<&str> = parse_phrases_file(include_str!(
let (phrases, exceptions) = parse_phrases_file(include_str!(
"lists/sensitive-topics-and-triggering-content.txt"
));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -600,29 +677,33 @@ impl Rule for SensitiveTopicsAndTriggeringContentRule {
}
fn action(&self) -> &'static Action {
&Action::BlockAndPenalty
&Action::SoftCensorAndWarn
}
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
pub struct MildSwearWordsRule(Regex);
#[derive(Debug)]
pub struct MildSwearWordsRule {
pattern: Regex,
exceptions: Vec<String>,
}
impl MildSwearWordsRule {
fn new() -> Self {
let phrases: Vec<&str> = parse_phrases_file(include_str!("lists/mild-swear-words.txt"));
let (phrases, exceptions) = parse_phrases_file(include_str!("lists/mild-swear-words.txt"));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -638,24 +719,28 @@ impl Rule for MildSwearWordsRule {
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
pub struct CasualInsultsAndTeasing(Regex);
#[derive(Debug)]
pub struct CasualInsultsAndTeasing {
pattern: Regex,
exceptions: Vec<String>,
}
impl CasualInsultsAndTeasing {
fn new() -> Self {
let phrases: Vec<&str> =
let (phrases, exceptions) =
parse_phrases_file(include_str!("lists/casual-insults-and-teasing.txt"));
let regex = regex_from_phrases_list(&phrases);
Self(regex)
Self {
pattern: regex,
exceptions,
}
}
}
@@ -671,14 +756,11 @@ impl Rule for CasualInsultsAndTeasing {
fn detect(&self, _original: &str, normalized: &str) -> (Vec<String>, Vec<String>) {
(
vec![],
self.0
.find_iter(normalized)
.map(|m| normalized[m.start()..m.end()].to_string())
.collect(),
find_with_exceptions(normalized, &self.pattern, &self.exceptions),
)
}
}
#[derive(Debug)]
struct LinksRule;
impl Rule for LinksRule {
@@ -702,6 +784,10 @@ impl Rule for LinksRule {
(detections, vec![])
}
fn ignore_for_moderators(&self) -> bool {
true
}
}
/// The list of moderation rules.
+103 -20
View File
@@ -1,37 +1,120 @@
use async_trait::async_trait;
use time::{Duration, UtcDateTime};
use twilight_util::snowflake::Snowflake;
use crate::{
database::models::UserIncident,
framework::commands::{CommandError, context::CommandContext, permissions::Permission},
groups::calls::components::{CodeOfConductButton, NeedHelpButton},
state::State,
};
use crate::database::models::{Channel, Participant, UserIncident};
use crate::extras::Extras;
use crate::framework::commands::CommandError;
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::groups::calls::components::{CodeOfConductButton, NeedHelpButton};
use crate::state::State;
#[derive(Debug)]
pub struct NotBannedPermission;
#[async_trait]
impl Permission<State> for NotBannedPermission {
async fn check(&self, ctx: &CommandContext<State>) -> Result<bool, CommandError> {
impl Permission<State, Extras> for NotBannedPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
let incidents = UserIncident::get_for_user(ctx.event.author.id.get(), &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get user incidents: {e}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?;
.inspect_err(|e| log::error!("Failed to get user incidents: {e}"))?;
if incidents.iter().any(|i| i.is_active()) {
ctx.send()
.content("❌ You've been banned from Payphone.")
.component(CodeOfConductButton, 1)
.component(NeedHelpButton, 1)
.await
.inspect_err(|e| {
log::error!("Failed to send message: {e}");
})
.map_err(|_| CommandError::MessageSendingFailed)?;
Ok(false)
} else {
Ok(true)
}
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("❌ You've been banned from Payphone.")
.component(CodeOfConductButton, 1)
.component(NeedHelpButton, 1)
.await
.inspect_err(|e| {
log::error!("Failed to send message: {e}");
})?;
Ok(())
}
}
#[derive(Debug)]
pub struct NonNewAccountPermission;
#[async_trait]
impl Permission<State, Extras> for NonNewAccountPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
Ok(ctx.event.author.id.get() == ctx.rt.state.bot_owner_id
|| UtcDateTime::from_unix_timestamp(ctx.event.author.id.timestamp() / 1000).unwrap()
< UtcDateTime::now() - Duration::days(30))
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("❌ Your account must be at least 30 days old to use Payphone.")
.component(CodeOfConductButton, 1)
.component(NeedHelpButton, 1)
.await
.inspect_err(|e| {
log::error!("Failed to send message: {e}");
})?;
Ok(())
}
}
/// Requires users to have sent a message in the call to be able to use the command.
///
/// This is to prevent abuse of commands by lurkers in the call, as well as to prevent
/// non-participants from skipping or ending calls they're not in.
#[derive(Debug)]
pub struct IsCallParticipantPermission;
#[async_trait]
impl Permission<State, Extras> for IsCallParticipantPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
let channel = match Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db).await?
{
Some(channel) => channel,
None => return Ok(true), // The channel isn't in the database, so it can't be in call.
};
let call_id = match channel.call_id {
Some(call_id) => call_id,
None => return Ok(true), // The channel isn't in a call, so the user can use commands in it.
};
let participants = Participant::get_for_call(call_id, &ctx.rt.state.db).await?;
for participant in participants {
if participant.user_id == ctx.event.author.id.get() {
return Ok(true);
}
}
return Ok(false);
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("❌ You haven't sent any messages on this call. You cannot run this command.")
.await
.inspect_err(|e| {
log::error!("Failed to send message: {e}");
})?;
Ok(())
}
}
+142
View File
@@ -0,0 +1,142 @@
use once_cell::sync::Lazy;
use rand::SeedableRng;
use rand::seq::IndexedRandom;
use rand_chacha::ChaCha20Rng;
static STRINGS_TIPS: Lazy<Vec<String>> = Lazy::new(|| {
let json = include_str!("strings/tips.json");
let strings: Vec<String> =
serde_json::from_str(json).expect("Failed to parse strings/tips.json strings");
assert_ne!(strings.len(), 0, "No strings found in strings/tips.json");
strings
});
pub fn get_string_tips(prefix: &str) -> String {
let mut rng = ChaCha20Rng::from_os_rng();
let message = STRINGS_TIPS
.choose(&mut rng)
.expect("Failed to choose a random string from tips");
message.replace("{prefix}", prefix)
}
static STRINGS_CALL_ANSWERED: Lazy<Vec<String>> = Lazy::new(|| {
let json = include_str!("strings/call-answered.json");
let strings: Vec<String> =
serde_json::from_str(json).expect("Failed to parse strings/call-answered.json strings");
assert_ne!(
strings.len(),
0,
"No strings found in strings/call-answered.json"
);
strings
});
pub fn get_string_call_answered(prefix: &str) -> String {
let mut rng = ChaCha20Rng::from_os_rng();
let message = STRINGS_CALL_ANSWERED
.choose(&mut rng)
.expect("Failed to choose a random string from call answered strings");
message.replace("{prefix}", prefix)
}
static STRINGS_CALL_SEARCHING: Lazy<Vec<String>> = Lazy::new(|| {
let json = include_str!("strings/call-searching.json");
let strings: Vec<String> =
serde_json::from_str(json).expect("Failed to parse strings/call-searching.json strings");
assert_ne!(
strings.len(),
0,
"No strings found in strings/call-searching.json"
);
strings
});
pub fn get_string_call_searching(prefix: &str) -> String {
let mut rng = ChaCha20Rng::from_os_rng();
let message = STRINGS_CALL_SEARCHING
.choose(&mut rng)
.expect("Failed to choose a random string from call starting strings");
message.replace("{prefix}", prefix)
}
static STRINGS_CALL_NO_ANSWER: Lazy<Vec<String>> = Lazy::new(|| {
let json = include_str!("strings/call-no-answer.json");
let strings: Vec<String> =
serde_json::from_str(json).expect("Failed to parse strings/call-no-answer.json strings");
assert_ne!(
strings.len(),
0,
"No strings found in strings/call-no-answer.json"
);
strings
});
pub fn get_string_call_no_answer(prefix: &str) -> String {
let mut rng = ChaCha20Rng::from_os_rng();
let message = STRINGS_CALL_NO_ANSWER
.choose(&mut rng)
.expect("Failed to choose a random string from call no answer strings");
message.replace("{prefix}", prefix)
}
static STRINGS_CALL_HANGUP_THIS_PARTY: Lazy<Vec<String>> = Lazy::new(|| {
let json = include_str!("strings/call-hangup-this-party.json");
let strings: Vec<String> = serde_json::from_str(json)
.expect("Failed to parse strings/call-hangup-this-party.json strings");
assert_ne!(
strings.len(),
0,
"No strings found in strings/call-hangup-this-party.json"
);
strings
});
pub fn get_string_call_hangup_this_party(prefix: &str) -> String {
let mut rng = ChaCha20Rng::from_os_rng();
let message = STRINGS_CALL_HANGUP_THIS_PARTY
.choose(&mut rng)
.expect("Failed to choose a random string from call hangup this party strings");
message.replace("{prefix}", prefix)
}
static STRINGS_CALL_HANGUP_OTHER_PARTY: Lazy<Vec<String>> = Lazy::new(|| {
let json = include_str!("strings/call-hangup-other-party.json");
let strings: Vec<String> = serde_json::from_str(json)
.expect("Failed to parse strings/call-hangup-other-party.json strings");
assert_ne!(
strings.len(),
0,
"No strings found in strings/call-hangup-other-party.json"
);
strings
});
pub fn get_string_call_hangup_other_party(prefix: &str) -> String {
let mut rng = ChaCha20Rng::from_os_rng();
let message = STRINGS_CALL_HANGUP_OTHER_PARTY
.choose(&mut rng)
.expect("Failed to choose a random string from call hangup other party strings");
message.replace("{prefix}", prefix)
}
@@ -0,0 +1,12 @@
[
"Call connected! You're live!",
"The call was answered.",
"Someone picked up the call!",
"Connected! Start talking.",
"You're now connected!",
"The call was successfully answered.",
"Call picked up! You're connected.",
"You're now live on the call!",
"Call answered. Go ahead!",
"Connection successful! You're live."
]
@@ -0,0 +1,12 @@
[
"The other party has hung up.",
"Call ended by the other party.",
"The other person disconnected.",
"The call was terminated by the other party.",
"The other person has hung up.",
"Conversation ended by the other party.",
"The call has been finished by the other party.",
"The other party ended the call.",
"Disconnected by the other party.",
"The other person ended the call."
]
@@ -0,0 +1,12 @@
[
"Call ended. You hung up.",
"You've disconnected the call.",
"You ended the call.",
"Call terminated. You hung up.",
"You have hung up the call.",
"You ended the conversation.",
"You've finished the call.",
"Call ended by you.",
"You disconnected the call.",
"You have ended the call."
]
@@ -0,0 +1,12 @@
[
"No answer. Maybe try again later?",
"It looks like nobody picked up.",
"The call went unanswered.",
"No response. Try calling again later.",
"No one is available to answer.",
"The call wasn't answered.",
"Nobody answered the call.",
"The call went unanswered. Try again soon!",
"No answer at the moment.",
"The call wasn't picked up."
]
@@ -0,0 +1,12 @@
[
"Dialing now! Please wait...",
"Trying to connect you...",
"Making the call, hang tight!",
"Searching for someone to answer...",
"Your call is being placed...",
"Connecting your call now...",
"Calling! One moment please...",
"Attempting to reach your contact...",
"Establishing the connection...",
"Your call is on the way!"
]
+20
View File
@@ -0,0 +1,20 @@
[
"Automod features are still under development! Join the [official Discord server](<https://discord.gg/9daSsrfTmE>) if you detect a bug and we'll help you out.",
"You can report messages using `Message > Apps > Report Message`.",
"Help us sharing Payphone to make it more active!",
"Emojis will only show if they're from a server Payphone's in.",
"You cannot send links.",
"[Vote for Payphone on top.gg](<https://top.gg/bot/1212940413795827763/vote>) to see more people around!",
"[Write a review](<https://top.gg/bot/1212940413795827763#reviews>) to tell everyone your opinion about Payphone!",
"Calls will be automatically hung up after 15 minutes if nobody talks.",
"You can change Payphone's prefix with `{prefix}prefix`.",
"You can use `{prefix}skip` to directly search for a new call.",
"Want to stay hidden? Use `{prefix}mask on`!",
"Did you know you can check your mask with `{prefix}mask`?",
"Do you like Payphone? Consider [making a donation](<https://ko-fi.com/payphonedev>) to help us grow Payphone (and keep it running)!",
"Using `{prefix}friendreq` is the best way to ask the other party to add you.",
"There's a secret easter egg command. Try to find it! (Hint: cat)",
"Make sure to read Payphone's [Code of Conduct](<https://payphone.lat/code-of-conduct>). Let's keep Payphone safe and fun for everyone!",
"Did you join [Payphone's new official server](<https://discord.gg/9daSsrfTmE>) yet? We have a lot of fun stuff there!",
"How high are you on the leaderboard? Use `{prefix}leaderboard` to check it out!"
]
+3
View File
@@ -0,0 +1,3 @@
[
"Thank you X and Anonymous Person for your support! We have covered next month's hosting costs."
]
+104
View File
@@ -0,0 +1,104 @@
use async_trait::async_trait;
use deadpool_redis::redis::AsyncTypedCommands;
use time::{Duration, UtcDateTime};
use twilight_model::id::Id;
use crate::database::models::Call;
use crate::extras::Extras;
use crate::framework::runtime::Runtime;
use crate::framework::tasks::Task;
use crate::state::State;
#[derive(Debug)]
pub struct EndInactiveCallsTask {
pub current_shard: u32,
pub total_shards: u32,
}
impl EndInactiveCallsTask {
pub fn new(current_shard: u32, total_shards: u32) -> Self {
Self {
current_shard,
total_shards,
}
}
}
#[async_trait]
impl Task<State, Extras> for EndInactiveCallsTask {
fn delay(&self) -> std::time::Duration {
std::time::Duration::from_secs(5)
}
async fn run(&self, rt: &Runtime<State, Extras>) -> anyhow::Result<()> {
let mut redis = rt.state.redis.get().await?;
let calls_and_channels = redis
.zrangebyscore(
"active-calls",
0,
(UtcDateTime::now() - Duration::minutes(10)).unix_timestamp(),
)
.await?;
let mut ended_call_ids = Vec::new();
for (call_id, channel_id) in calls_and_channels.iter().filter_map(|i| {
i.split_once(":").and_then(|(a, b)| {
let a = a.parse::<u64>().ok();
let b = b.parse::<u64>().ok();
a.zip(b)
})
}) {
if ended_call_ids.contains(&call_id) {
continue;
}
if (call_id) % self.total_shards as u64 != self.current_shard as u64 {
continue;
}
ended_call_ids.push(call_id);
let Ok(Some(call)) = Call::get_by_id(call_id, &rt.state.db).await else {
redis
.zrem("active-calls", format!("{call_id}:{channel_id}"))
.await
.inspect_err(|e| log::error!("Failed to remove inactive call from redis: {e}"))
.ok();
continue;
};
let channel_keys = [
format!("{call_id}:{}", call.channel_ids[0]),
format!("{call_id}:{}", call.channel_ids[1]),
];
redis
.zrem("active-calls", &channel_keys)
.await
.inspect_err(|e| log::error!("Failed to remove inactive call from redis: {e}"))
.ok();
call.hangup(&rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to hangup inactive call {call_id}: {e}"))
.ok();
for channel_id in call.channel_ids {
rt.http
.create_message(Id::new(channel_id))
.content("☎️ The call was hung up because one or both parties were gone for too long.")
.await
.inspect_err(|e| {
log::error!("Failed to send call end message to channel {channel_id}: {e}")
})
.ok();
}
}
Ok(())
}
}
+8 -11
View File
@@ -5,21 +5,18 @@ use std::sync::Arc;
use async_trait::async_trait;
use twilight_model::gateway::payload::incoming::Ready;
use crate::{
framework::{
events::traits::{EventResult, OnReadyHandler, OnReconnectHandler},
runtime::Runtime,
},
state::State,
};
use crate::extras::Extras;
use crate::framework::events::traits::{EventResult, OnReadyHandler, OnReconnectHandler};
use crate::framework::runtime::Runtime;
use crate::state::State;
/// Logs a ready message when the bot is ready.
#[derive(Debug)]
pub struct ReadyHandler;
#[async_trait]
impl OnReadyHandler<State> for ReadyHandler {
async fn on_ready(&self, event: &Ready, _: Arc<Runtime<State>>) -> EventResult {
impl OnReadyHandler<State, Extras> for ReadyHandler {
async fn on_ready(&self, event: &Ready, _: Arc<Runtime<State, Extras>>) -> EventResult {
log::info!(
"Ready! Logged in as {}#{:>04}",
event.user.name,
@@ -35,8 +32,8 @@ impl OnReadyHandler<State> for ReadyHandler {
pub struct ReconnectHandler;
#[async_trait]
impl OnReconnectHandler<State> for ReconnectHandler {
async fn on_reconnect(&self, _: Arc<Runtime<State>>) -> EventResult {
impl OnReconnectHandler<State, Extras> for ReconnectHandler {
async fn on_reconnect(&self, _: Arc<Runtime<State, Extras>>) -> EventResult {
log::info!("The gateway asked for a reconnection");
Ok(())
+151
View File
@@ -0,0 +1,151 @@
use async_trait::async_trait;
use deadpool_redis::redis::AsyncCommands;
use itertools::Itertools;
use twilight_util::builder::embed::{
EmbedAuthorBuilder, EmbedBuilder, EmbedFooterBuilder, ImageSource,
};
use crate::constants::COLOR_WHITE;
use crate::database::models::User;
use crate::discord::images;
use crate::discord::sanitizing::SanitizeDiscordMarkdown;
use crate::extras::Extras;
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::{Command, CommandError};
use crate::groups::leveling::constants::KEY_LEADERBOARD_MONTHLY;
use crate::state::State;
use crate::utils::format_thousands;
#[derive(Debug)]
pub struct LeaderboardCommand;
#[async_trait]
impl Command<State, Extras> for LeaderboardCommand {
fn name(&self) -> &'static str {
"leaderboard"
}
fn aliases(&self) -> &'static [&'static str] {
&["lb"]
}
fn description(&self) -> &'static str {
"Lists the top users in the leaderboard and your position in it."
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
_args: &str,
) -> Result<(), CommandError> {
let mut redis = ctx.rt.state.redis.get().await?;
let top: Vec<(u64, f64)> = redis
.zrevrange_withscores(KEY_LEADERBOARD_MONTHLY, 0, 9)
.await?;
log::trace!("Top users for leaderboard: {top:?}");
let current_user_rank: Option<usize> = redis
.zrevrank(KEY_LEADERBOARD_MONTHLY, ctx.event.author.id.get())
.await?;
let current_user_xp: Option<f64> = redis
.zscore(KEY_LEADERBOARD_MONTHLY, ctx.event.author.id.get())
.await?;
let current_user_xp = current_user_xp.map(|xp| xp as u64);
let current_user_rank_and_xp = current_user_rank.zip(current_user_xp);
let mut users = Vec::new();
for (user_id, score) in top {
let Some(user) = User::get_by_id(user_id, &ctx.rt.state.db).await? else {
log::trace!("User ID {user_id} not found for leaderboard");
continue;
};
if let Some(is_banned_from_leaderboard) = user.is_banned_from_leaderboard
&& is_banned_from_leaderboard
{
log::trace!(
"Skipping user {} (ID: {}) because they are banned from the leaderboard.",
user.name,
user.id
);
continue;
}
users.push((user, score as u32));
}
let description = if !users.is_empty() {
users
.iter()
.enumerate()
.map(|(i, (user, xp))| {
format!(
"#{}: **{}** - {} XP",
i + 1,
user.name.sanitize(true),
format_thousands(*xp as u64)
)
})
.join("\n")
} else {
"*Nobody earned XP this month yet.*".to_string()
};
let footer = if let Some((rank, xp)) = current_user_rank_and_xp {
format!(
"Your current rank: #{} - {} XP",
rank + 1,
format_thousands(xp)
)
} else {
"You haven't earned XP this month yet.".to_string()
};
let embed = EmbedBuilder::new()
.color(COLOR_WHITE)
.title("Monthly Leaderboard")
.description(description)
.author(
EmbedAuthorBuilder::new(ctx.rt.app.name.clone()).icon_url(
ImageSource::url(images::get_avatar_url(
ctx.rt.app.bot.as_ref().unwrap().avatar,
ctx.rt.app.bot.as_ref().unwrap().id.get(),
ctx.rt.app.bot.as_ref().unwrap().discriminator as u64,
None,
))
.unwrap(),
),
)
.thumbnail(
ImageSource::url(images::get_avatar_url(
ctx.rt.app.bot.as_ref().unwrap().avatar,
ctx.rt.app.bot.as_ref().unwrap().id.get(),
ctx.rt.app.bot.as_ref().unwrap().discriminator as u64,
None,
))
.unwrap(),
)
.footer(
EmbedFooterBuilder::new(footer).icon_url(
ImageSource::url(images::get_avatar_url(
ctx.event.author.avatar,
ctx.event.author.id.get(),
ctx.event.author.discriminator as u64,
None,
))
.unwrap(),
),
);
ctx.send()
.embed(embed.build())
.await
.inspect_err(|e| log::error!("Failed to send leaderboard embed: {e}"))?;
Ok(())
}
}
+1
View File
@@ -0,0 +1 @@
pub(super) const KEY_LEADERBOARD_MONTHLY: &str = "lvl:monthly";
+110
View File
@@ -0,0 +1,110 @@
use std::sync::Arc;
use async_trait::async_trait;
use deadpool_redis::redis::{AsyncTypedCommands, IntegerReplyOrNoOp};
use rand::{Rng, SeedableRng};
use rand_chacha::ChaCha20Rng;
use time::{Date, Month, OffsetDateTime, Time};
use twilight_model::gateway::payload::incoming::MessageCreate;
use crate::database::models::Channel;
use crate::extras::Extras;
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::events::traits::{EventResult, OnMessageHandler};
use crate::framework::runtime::Runtime;
use crate::groups::leveling::constants::KEY_LEADERBOARD_MONTHLY;
use crate::state::State;
fn seconds_until_end_of_month() -> i64 {
let now = OffsetDateTime::now_utc();
let year = now.year();
let month = now.month();
// figure out the first day of the next month
let (next_year, next_month) = if month == Month::December {
(year + 1, Month::January)
} else {
(year, month.next())
};
let first_of_next_month = Date::from_calendar_date(next_year, next_month, 1)
.unwrap()
.with_time(Time::MIDNIGHT)
.assume_utc();
(first_of_next_month - now).whole_seconds()
}
#[derive(Debug)]
pub struct MessageLevelingHandler;
#[async_trait]
impl OnMessageHandler<State, Extras> for MessageLevelingHandler {
async fn on_message(
&self,
event: &MessageCreate,
rt: Arc<Runtime<State, Extras>>,
_extras: Arc<dyn ExtrasGetter<State, Extras = Extras>>,
) -> EventResult {
if event.author.bot || event.author.system.unwrap_or(false) {
return Ok(());
}
let prefixes = rt
.get_prefixes(event.guild_id.map(|i| i.get()), Some(event.author.id.get()))
.await;
if prefixes.iter().any(|prefix| {
event
.content
.to_ascii_lowercase()
.starts_with(&prefix.to_ascii_lowercase())
}) {
return Ok(());
}
let Some(channel) = Channel::get_by_id(event.channel_id.get(), &rt.state.db).await? else {
return Ok(());
};
if channel.call_id.is_none() {
return Ok(());
}
let mut redis = rt.state.redis.get().await?;
let key = format!("lvl:{}", event.author.id);
let lock = redis.ttl(&key).await?;
if let IntegerReplyOrNoOp::IntegerReply(seconds) = lock {
log::trace!(
"No XP for the message because the user is already in the cooldown period. Remaining seconds: {seconds}"
);
return Ok(());
}
let xp = ChaCha20Rng::from_os_rng().random_range(10..=25);
log::trace!(
"Adding {xp} XP to user {} in channel {}",
event.author.name,
event.channel_id
);
redis.set_ex(&key, "", 60).await?;
redis
.zincr(KEY_LEADERBOARD_MONTHLY, event.author.id.get(), xp)
.await?;
let leaderboard_exat = redis.ttl(KEY_LEADERBOARD_MONTHLY).await?;
if leaderboard_exat == IntegerReplyOrNoOp::ExistsButNotRelevant {
redis
.expire(KEY_LEADERBOARD_MONTHLY, seconds_until_end_of_month())
.await?;
}
Ok(())
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod commands;
pub mod constants;
pub mod events;
+2
View File
@@ -17,4 +17,6 @@
pub mod about;
pub mod calls;
pub mod gateway;
pub mod leveling;
pub mod moderation;
pub mod servers;
+268
View File
@@ -0,0 +1,268 @@
use std::ops::{Deref, DerefMut};
use std::time::Duration;
use scylla::client::session::Session;
use crate::database::models::{Channel, Message, User};
use crate::extras::Extras;
use crate::framework::commands::arguments::{ArgumentParsingError, FromArguments, NeedyString};
use crate::framework::commands::context::CommandContext;
use crate::state::State;
use crate::utils::split_at_nth_from_end;
/// Fetch a user by their ID from the database.
///
/// Arguments:
/// * `id` - The user's ID.
/// * `db` - The database session.
///
/// Returns:
/// [`Result<User, ArgumentParser>`] - The user from the DB, or an [`ArgumentParsingError`] ready
/// to be returned by the parser.
async fn get_user_by_id(id: u64, db: &Session) -> Result<User, ArgumentParsingError> {
let user = User::get_by_id(id, db).await?;
match user {
Some(user) => Ok(user),
None => Err(ArgumentParsingError::InvalidArgument),
}
}
/// Fetches the user from the message's reply and falls back to the command executor.
///
/// This function takes into account messages on call and traces them back to the original author.
///
/// Arguments:
/// * `ctx` - The command context.
///
/// Returns:
/// [`Result<User, ArgumentParsingError>`] - The user from the message's reply, or an
/// [`ArgumentParsingError`] ready to be returned by the parser.
async fn user_from_reply_or_command_executor(
ctx: &CommandContext<'_, State, Extras>,
) -> Result<User, ArgumentParsingError> {
if let Some(referenced) = &ctx.event.referenced_message
&& !referenced.author.system.unwrap_or(false)
{
if referenced.author.bot
&& let Some(message) =
Message::get_by_propagation_message_id(referenced.id.get(), &ctx.rt.state.db)
.await?
{
return get_user_by_id(message.author_id, &ctx.rt.state.db).await;
}
// If the replied message's author is not a bot or system user, use them.
return get_user_by_id(referenced.author.id.get(), &ctx.rt.state.db).await;
}
// fallback to command executor
get_user_by_id(ctx.event.author.id.get(), &ctx.rt.state.db).await
}
/// Parses a user mention or ID into a UserArgument.
///
/// It parses from multiple sources, attempting in the following way:
///
/// 1. If the argument is a Discord mention, parsing it.
/// 2. If the argument is a Discord ID, finding it in the DB.
/// 3. If the argument is a Discord mention, finding it in the DB.
/// 4. If there's no argument and the message replies to another message:
/// a. If the replied message's author is a bot, attempts to query the user who sent it from the
/// other side of the call. If it fails, the command executor is used.
/// b. If the replied message's author is not a bot, they're used.
/// 5. If there's no argument and the message is not replying to any message, the command executor
/// is used.
pub struct UserArgument(pub User);
impl FromArguments<State, Extras> for UserArgument {
async fn from_args<'a>(
args: &'a str,
ctx: &'a CommandContext<'_, State, Extras>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
if !args.is_empty() {
// There's an argument, so that argument is used to find the user.
let user: User;
let (identifier, args) = NeedyString::from_args(args, ctx).await?;
let identifier = identifier.0.trim();
if identifier.starts_with("<@") && identifier.ends_with(">") {
// The argument is a Discord mention.
let user_id: u64 = identifier[2..identifier.len() - 1]
.to_string()
.parse()
.map_err(|_| ArgumentParsingError::InvalidArgument)?;
user = get_user_by_id(user_id, &ctx.rt.state.db).await?;
} else if identifier.chars().all(|c| c.is_ascii_digit()) {
// The argument is a user ID.
let user_id: u64 = identifier
.parse()
.map_err(|_| ArgumentParsingError::InvalidArgument)?;
match get_user_by_id(user_id, &ctx.rt.state.db).await {
Ok(result) => user = result,
Err(error) => {
if matches!(error, ArgumentParsingError::InvalidArgument) {
let message =
Message::get_by_propagation_message_id(user_id, &ctx.rt.state.db)
.await?;
if let Some(message) = message {
user = get_user_by_id(message.author_id, &ctx.rt.state.db).await?;
} else {
return Err(ArgumentParsingError::InvalidArgument);
}
} else {
return Err(error);
}
}
}
} else {
// The argument is (probably) a username.
let Some(db_user) =
User::get_by_name(identifier.to_string(), &ctx.rt.state.db).await?
else {
// Check in the message's reply, and if not use the command executor.
user = user_from_reply_or_command_executor(ctx).await?;
return Ok((UserArgument(user), args));
};
user = db_user;
}
// Notice that `args` is shadowed above, so this line can't be removed (or else the
// full args will be passed and not just the remaining ones as it should be).
Ok((UserArgument(user), args))
} else {
// Check in the message's reply, and if not use the command executor.
let user = user_from_reply_or_command_executor(ctx).await?;
Ok((UserArgument(user), args))
}
}
}
impl Deref for UserArgument {
type Target = User;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for UserArgument {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug, Clone, Copy)]
pub struct DurationArgument(pub Duration);
impl FromArguments<State, Extras> for DurationArgument {
async fn from_args<'a>(
mut args: &'a str,
_ctx: &'a CommandContext<'_, State, Extras>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
let mut i = 1;
let mut finding = None;
while let Some((substring, remaining_args)) = split_at_nth_from_end(args, " ", i) {
if let Ok(duration) = humantime::parse_duration(substring) {
finding = Some(DurationArgument(duration));
args = remaining_args;
break;
}
i += 1;
}
if let Some(duration) = finding {
Ok((duration, args))
} else {
Err(ArgumentParsingError::InvalidArgument)
}
}
}
impl Deref for DurationArgument {
type Target = Duration;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for DurationArgument {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[derive(Debug, Clone)]
pub struct ChannelArgument(pub Channel);
impl FromArguments<State, Extras> for ChannelArgument {
async fn from_args<'a>(
args: &'a str,
ctx: &'a CommandContext<'_, State, Extras>,
) -> Result<(Self, &'a str), ArgumentParsingError> {
let (identifier, args) = NeedyString::from_args(args, ctx).await?;
let identifier = identifier.0.trim();
if identifier == "." || identifier == "this" || identifier == "here" {
let channel = Channel::get_by_id(ctx.event.channel_id.get(), &ctx.rt.state.db).await?;
if let Some(channel) = channel {
return Ok((Self(channel), args));
}
} else if identifier.starts_with("<#") && identifier.ends_with(">") {
// The argument is a Discord mention.
let channel_id: u64 = identifier[2..identifier.len() - 1]
.to_string()
.parse()
.map_err(|_| ArgumentParsingError::InvalidArgument)?;
let channel = Channel::get_by_id(channel_id, &ctx.rt.state.db).await?;
if let Some(channel) = channel {
return Ok((Self(channel), args));
}
} else {
let channel_id: u64 = identifier
.parse()
.map_err(|_| ArgumentParsingError::InvalidArgument)?;
let channel = Channel::get_by_id(channel_id, &ctx.rt.state.db).await?;
if let Some(channel) = channel {
return Ok((Self(channel), args));
}
}
Err(ArgumentParsingError::MissingArgument)
}
}
impl Deref for ChannelArgument {
type Target = Channel;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for ChannelArgument {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
+362
View File
@@ -0,0 +1,362 @@
use async_trait::async_trait;
use deadpool_redis::redis::AsyncTypedCommands;
use time::UtcDateTime;
use crate::database::models::{Call, UserIncident, UserIncidentType};
use crate::extras::Extras;
use crate::framework::commands::arguments::{
Arg, Argument, ArgumentParsingError, NeedyGreedyString, ParseArguments,
};
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::framework::commands::{Command, CommandError};
use crate::framework::runtime::Runtime;
use crate::groups::moderation::arguments::{ChannelArgument, DurationArgument, UserArgument};
use crate::groups::moderation::get_incident_page;
use crate::groups::moderation::permissions::{BotModeratorPermission, BotOwnerPermission};
use crate::state::State;
use crate::utils::{Bye, get_random_u64};
#[derive(Debug)]
pub struct ModeratorCommand;
#[async_trait]
impl Command<State, Extras> for ModeratorCommand {
fn name(&self) -> &'static str {
"moderator"
}
fn aliases(&self) -> &'static [&'static str] {
&["mod"]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![Box::new(BotOwnerPermission)]
}
fn show_in_help(&self, rt: &Runtime<State, Extras>, extras: &Extras) -> bool {
extras.user.id == rt.state.bot_owner_id
}
fn arguments(&self) -> &'static [Argument] {
&[Argument {
name: "user",
is_optional: false,
is_greedy: false,
}]
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let Arg(mut user) = match Arg::<UserArgument>::parse(args, &ctx).await {
Ok(arg) => arg,
Err(e) => match e {
ArgumentParsingError::InvalidArgument => {
ctx.send().content("❌ User not found in DB.").await?;
return Ok(());
}
ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed(e));
}
e => {
unreachable!("Unexpected error: {e}");
}
},
};
user.is_moderator = !user.is_moderator;
user.insert(&ctx.rt.state.db).await?;
ctx.send()
.content(format!(
"👍 Done. <@{}> {}",
user.id,
if user.is_moderator {
"**is now** a moderator"
} else {
"**is no longer** a moderator"
}
))
.await?;
Ok(())
}
}
#[derive(Debug)]
pub struct IncidentsCommand;
#[async_trait]
impl Command<State, Extras> for IncidentsCommand {
fn name(&self) -> &'static str {
"incidents"
}
fn aliases(&self) -> &'static [&'static str] {
&["i"]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![Box::new(BotModeratorPermission)]
}
fn arguments(&self) -> &'static [Argument] {
&[Argument {
name: "user",
is_optional: false,
is_greedy: false,
}]
}
fn show_in_help(&self, _rt: &Runtime<State, Extras>, extras: &Extras) -> bool {
extras.user.is_moderator
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let user = match Arg::<UserArgument>::parse(args, &ctx).await {
Ok(Arg(user)) => user,
Err(e) => match e {
ArgumentParsingError::InvalidArgument => {
ctx.send().content("❌ User not found in DB.").await?;
return Ok(());
}
ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed(e));
}
e => {
unreachable!("Unexpected error: {e}");
}
},
};
let message = get_incident_page(user.id, &ctx.rt.state.db, 0).await?;
ctx.send_from_builder(message).await?;
Ok(())
}
}
#[derive(Debug)]
pub struct BanCommand;
#[async_trait]
impl Command<State, Extras> for BanCommand {
fn name(&self) -> &'static str {
"ban"
}
fn aliases(&self) -> &'static [&'static str] {
&["b"]
}
fn description(&self) -> &'static str {
"Bans a user from Payphone calls.\n\nThe user can be specified via either replying to them (works on call too), mentioning them, specifying their username, specifying their ID, or not setting it to default to yourself.\n\nThe duration can be specified as defined in the [`humantime::parse_duration` documentation](https://docs.rs/humantime/latest/humantime/fn.parse_duration.html)."
}
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![Box::new(BotModeratorPermission)]
}
fn show_in_help(&self, _rt: &Runtime<State, Extras>, extras: &Extras) -> bool {
extras.user.is_moderator
}
fn arguments(&self) -> &'static [Argument] {
&[
Argument {
name: "user",
is_optional: false,
is_greedy: false,
},
Argument {
name: "duration",
is_optional: true,
is_greedy: false,
},
Argument {
name: "reason",
is_optional: false,
is_greedy: true,
},
]
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let (user, duration, reason) = match <(
UserArgument,
Option<DurationArgument>,
NeedyGreedyString,
)>::parse(args, &ctx)
.await
{
Ok(arg) => arg,
Err(e) => match e {
ArgumentParsingError::InvalidArgument => {
ctx.send()
.content("❌ User not found in DB or no reason was provided.")
.await?;
return Ok(());
}
ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed(e));
}
ArgumentParsingError::MissingArgument => {
ctx.send().content(format!("❌ No reason was provided. Use `{}help ban` to learn how to use this command.", ctx.prefix)).await?;
return Ok(());
}
},
};
let incident = UserIncident {
created_at: UtcDateTime::now(),
user_id: user.id,
incident_id: get_random_u64(),
report_id: None,
r#type: UserIncidentType::Ban,
message: None,
created_by_id: Some(ctx.event.author.id.get()),
reason: (*reason).clone(),
expires_at: duration.map(|d| UtcDateTime::now() + *d),
duration: duration.map(|d| humantime::format_duration(*d).to_string()),
};
incident.insert(&ctx.rt.state.db).await?;
ctx.send()
.content(format!(
"✅ User `{}` has been banned from Payphone{}.",
user.name,
duration
.map(|d| format!(" for {}", humantime::format_duration(*d)))
.unwrap_or_default()
))
.await?;
Ok(())
}
}
#[derive(Debug)]
pub struct RemoteHangupCommand;
#[async_trait]
impl Command<State, Extras> for RemoteHangupCommand {
fn name(&self) -> &'static str {
"remotehangup"
}
fn aliases(&self) -> &'static [&'static str] {
&["rh"]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![Box::new(BotModeratorPermission)]
}
fn show_in_help(&self, _rt: &Runtime<State, Extras>, extras: &Extras) -> bool {
extras.user.is_moderator
}
fn arguments(&self) -> &'static [Argument] {
&[Argument {
name: "channel",
is_optional: false,
is_greedy: false,
}]
}
async fn execute(
&self,
ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let Arg(mut channel) = match Arg::<ChannelArgument>::parse(args, &ctx).await {
Ok(arg) => arg,
Err(e) => match e {
ArgumentParsingError::InvalidArgument => {
ctx.send().content("❌ Channel not found in DB.").await?;
return Ok(());
}
ArgumentParsingError::DatabaseFailed(e) => {
return Err(CommandError::DatabaseFailed(e));
}
e => {
unreachable!("Unexpected error: {e}");
}
},
};
if channel.is_searching {
channel
.cancel_search(&ctx.rt.state.db)
.await
.inspect_err(|e| {
log::error!("Failed to cancel search: {e:?}");
})?;
ctx.send()
.content("The channel was remotely made to stop searching for a call!")
.await?;
return Ok(());
}
if let Some(call_id) = channel.call_id {
let mut redis = ctx.rt.state.redis.get().await?;
let Some(call) = Call::get_by_id(call_id, &ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to get call: {e:?}"))?
else {
ctx.send().content("❌ The call could not be found.\n-# This is not supposed to happen. The channel is pointing to an ID in the database that does not exist.").await?;
channel.call_id = None;
channel.upsert(&ctx.rt.state.db).await.bye();
redis
.zrem("active-calls", format!("{}:{}", call_id, channel.id))
.await
.bye();
return Err(CommandError::DatabaseInconsistentState);
};
let channel_keys = [
format!("{call_id}:{}", call.channel_ids[0]),
format!("{call_id}:{}", call.channel_ids[1]),
];
redis
.zrem("active-calls", &channel_keys)
.await
.inspect_err(|e| log::error!("Failed to remove inactive call from redis: {e}"))
.ok();
call.hangup(&ctx.rt.state.db)
.await
.inspect_err(|e| log::error!("Failed to hang up call: {e:?}"))?;
ctx.send().content(format!("<#{}> had its call hung up.", channel.id)).await?;
} else {
ctx.send()
.content("❌ This channel is not in a call.")
.await?;
return Ok(());
}
Ok(())
}
}
+190
View File
@@ -0,0 +1,190 @@
use async_trait::async_trait;
use twilight_model::channel::message::component::ButtonStyle;
use crate::database::models::UserIncident;
use crate::extras::Extras;
use crate::framework::interactions::InteractionError;
use crate::framework::interactions::components::Button;
use crate::framework::interactions::context::InteractionContext;
use crate::groups::moderation::get_incident_page;
use crate::state::State;
use crate::utils::get_random_u64;
#[derive(Debug)]
pub struct ArrowIncidentButton {
pub arrow: &'static str,
pub user_id: u64,
pub go_to: Option<usize>,
}
#[async_trait]
impl Button<State, Extras> for ArrowIncidentButton {
fn id(&self) -> Option<String> {
Some(format!("incidents:arrow:{}", get_random_u64()))
}
fn label(&self) -> Option<String> {
Some(self.arrow.to_string())
}
fn disabled(&self) -> bool {
self.go_to.is_none()
}
async fn on_press(
&self,
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
if !ctx.extras.user.is_moderator {
ctx.defer().await?;
return Ok(());
}
if let Some(go_to) = self.go_to {
ctx.edit_original_message(
get_incident_page(self.user_id, &ctx.rt.state.db, go_to)
.await
.inspect_err(|e| log::error!("Failed to get incident page: {e:?}"))?
.into(),
)
.await
.inspect_err(|e| log::error!("Failed to edit original message: {e:?}"))?;
} else {
ctx.defer().await?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct CounterButton {
pub current: usize,
pub total: usize,
}
#[async_trait]
impl Button<State, Extras> for CounterButton {
fn id(&self) -> Option<String> {
Some("incidents:counter".into())
}
fn label(&self) -> Option<String> {
Some(format!("{}/{}", self.current, self.total))
}
fn disabled(&self) -> bool {
true
}
}
#[derive(Debug)]
pub struct ExpireIncidentButton {
pub user_id: u64,
pub incident_id: u64,
pub incident_index: usize,
pub is_enabled: bool,
}
#[async_trait]
impl Button<State, Extras> for ExpireIncidentButton {
fn id(&self) -> Option<String> {
Some(format!("incidents:expire:{}", get_random_u64()))
}
fn label(&self) -> Option<String> {
Some("Expire Incident".into())
}
fn style(&self) -> ButtonStyle {
ButtonStyle::Danger
}
fn disabled(&self) -> bool {
!self.is_enabled
}
async fn on_press(
&self,
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
if !ctx.extras.user.is_moderator {
ctx.defer().await?;
return Ok(());
}
UserIncident::expire_by_user_and_incident_id(
self.user_id,
self.incident_id,
&ctx.rt.state.db,
)
.await?;
ctx.edit_original_message(
get_incident_page(self.user_id, &ctx.rt.state.db, self.incident_index)
.await
.inspect_err(|e| log::error!("Failed to get incident page: {e:?}"))?
.into(),
)
.await
.inspect_err(|e| log::error!("Failed to edit original message: {e:?}"))?;
Ok(())
}
}
#[derive(Debug)]
pub struct DeleteIncidentButton {
pub user_id: u64,
pub incident_id: u64,
pub incident_index: usize,
}
#[async_trait]
impl Button<State, Extras> for DeleteIncidentButton {
fn id(&self) -> Option<String> {
Some(format!("incidents:delete:{}", get_random_u64()))
}
fn label(&self) -> Option<String> {
Some("Delete Incident".into())
}
fn style(&self) -> ButtonStyle {
ButtonStyle::Danger
}
fn disabled(&self) -> bool {
false
}
async fn on_press(
&self,
ctx: InteractionContext<State, Extras>,
) -> Result<(), InteractionError> {
if !ctx.extras.user.is_moderator {
ctx.defer().await?;
return Ok(());
}
UserIncident::delete_by_user_and_incident_id(
self.user_id,
self.incident_id,
&ctx.rt.state.db,
)
.await?;
let new_page_index = self.incident_index.saturating_sub(1);
ctx.edit_original_message(
get_incident_page(self.user_id, &ctx.rt.state.db, new_page_index)
.await
.inspect_err(|e| log::error!("Failed to get incident page: {e:?}"))?
.into(),
)
.await
.inspect_err(|e| log::error!("Failed to edit original message: {e:?}"))?;
Ok(())
}
}
+100
View File
@@ -0,0 +1,100 @@
use time::UtcDateTime;
use twilight_model::channel::message::Embed;
use twilight_util::builder::embed::{
EmbedAuthorBuilder, EmbedBuilder, EmbedFieldBuilder, ImageSource,
};
use crate::constants::{COLOR_RED, COLOR_YELLOW};
use crate::database::models::{UserIncident, UserIncidentType};
use crate::utils::ellipse;
fn format_timestamp(timestamp: UtcDateTime) -> String {
format!(
"<t:{}> (<t:{}:R>)",
timestamp.unix_timestamp(),
timestamp.unix_timestamp()
)
}
pub fn incident_embed(incident: &UserIncident) -> Embed {
if let Some(message) = &incident.message {
let mut builder = EmbedBuilder::new()
.color(match incident.r#type {
UserIncidentType::Ban => COLOR_RED,
UserIncidentType::Warning => COLOR_YELLOW,
})
.author(
EmbedAuthorBuilder::new(&message.author_name)
.icon_url(ImageSource::url(&message.author_avatar_url).unwrap()),
)
.title("Message Incident")
.thumbnail(ImageSource::url(message.author_avatar_url.clone()).unwrap())
.field(EmbedFieldBuilder::new("Message", ellipse(message.content.clone(), 100)).build())
.field(EmbedFieldBuilder::new("Author Name", message.author_name.clone()).build())
.field(
EmbedFieldBuilder::new(
"Author Avatar",
format!("[Click to open avatar](<{}>)", &message.author_avatar_url),
)
.build(),
)
.field(
EmbedFieldBuilder::new("Created At", format_timestamp(incident.created_at)).build(),
)
.field(EmbedFieldBuilder::new(
"Created By",
incident
.created_by_id
.map(|id| format!("<@{id}>"))
.unwrap_or("Automatic Moderator".into()),
));
if incident.r#type == UserIncidentType::Ban {
builder = builder.field(
EmbedFieldBuilder::new(
"Expires At",
incident
.expires_at
.map(format_timestamp)
.unwrap_or("*Never*".into()),
)
.build(),
);
}
builder.build()
} else {
let mut builder = EmbedBuilder::new()
.color(match incident.r#type {
UserIncidentType::Ban => COLOR_RED,
UserIncidentType::Warning => COLOR_YELLOW,
})
.title("Manual Incident")
.field(EmbedFieldBuilder::new("Reason", incident.reason.clone()))
.field(
EmbedFieldBuilder::new("Created At", format_timestamp(incident.created_at)).build(),
)
.field(EmbedFieldBuilder::new(
"Created By",
incident
.created_by_id
.map(|id| format!("<@{id}>"))
.unwrap_or("Automatic Moderator".into()),
));
if incident.r#type == UserIncidentType::Ban {
builder = builder.field(
EmbedFieldBuilder::new(
"Expires At",
incident
.expires_at
.map(format_timestamp)
.unwrap_or("*Never*".into()),
)
.build(),
);
}
builder.build()
}
}
+103
View File
@@ -0,0 +1,103 @@
use scylla::client::session::Session;
use crate::database::models::{DatabaseError, UserIncident, UserIncidentType};
use crate::extras::Extras;
use crate::framework::messages::MessageBuilder;
use crate::groups::moderation::components::{
ArrowIncidentButton, CounterButton, DeleteIncidentButton, ExpireIncidentButton,
};
use crate::groups::moderation::embeds::incident_embed;
use crate::state::State;
pub mod arguments;
pub mod commands;
pub mod components;
pub(super) mod embeds;
pub mod permissions;
pub(super) async fn get_incident_page(
user_id: u64,
session: &Session,
page_index: usize,
) -> Result<MessageBuilder<State, Extras>, DatabaseError> {
let mut incidents = UserIncident::get_for_user(user_id, session).await?;
incidents.sort_by(|a, b| b.created_at.cmp(&a.created_at));
if let Some(incident) = incidents.get(page_index) {
let mut builder = MessageBuilder::new()
.embed(incident_embed(incident))
.component(
ArrowIncidentButton {
arrow: "<<",
user_id,
go_to: if page_index > 0 { Some(0) } else { None },
},
1,
)
.component(
ArrowIncidentButton {
arrow: "<",
user_id,
go_to: if page_index > 0 {
Some(page_index - 1)
} else {
None
},
},
1,
)
.component(
CounterButton {
current: page_index + 1,
total: incidents.len(),
},
1,
)
.component(
ArrowIncidentButton {
arrow: ">",
user_id,
go_to: incidents.get(page_index + 1).map(|_| page_index + 1),
},
1,
)
.component(
ArrowIncidentButton {
arrow: ">>",
user_id,
go_to: if page_index + 1 < incidents.len() {
Some(incidents.len() - 1)
} else {
None
},
},
1,
);
if incident.r#type == UserIncidentType::Ban {
builder = builder.component(
ExpireIncidentButton {
incident_id: incident.incident_id,
incident_index: page_index,
user_id,
is_enabled: incident.is_active(),
},
2,
);
}
builder = builder.component(
DeleteIncidentButton {
incident_id: incident.incident_id,
incident_index: page_index,
user_id,
},
2,
);
Ok(builder)
} else {
Ok(MessageBuilder::new().content("No incidents found for this user."))
}
}
+50
View File
@@ -0,0 +1,50 @@
use async_trait::async_trait;
use crate::extras::Extras;
use crate::framework::commands::CommandError;
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::state::State;
#[derive(Debug)]
pub struct BotOwnerPermission;
#[async_trait]
impl Permission<State, Extras> for BotOwnerPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
Ok(ctx.extras.user.id == ctx.rt.state.bot_owner_id)
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("⛔ Not enough aura to run this command.")
.await?;
Ok(())
}
}
#[derive(Debug)]
pub struct BotModeratorPermission;
#[async_trait]
impl Permission<State, Extras> for BotModeratorPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
Ok(ctx.extras.user.is_moderator)
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("⛔ You're not a Payphone moderator.\n-# If you need to check your incidents, contact a Payphone moderator in the official server.")
.await
?;
Ok(())
}
}
+23 -24
View File
@@ -1,22 +1,21 @@
use async_trait::async_trait;
use crate::{
constants::DEFAULT_PREFIX,
database::models::Server,
discord::sanitizing::SanitizeDiscordMarkdown,
framework::commands::{
Command, CommandError,
arguments::{Argument, GreedyString, ParseArguments},
context::CommandContext,
},
state::State,
};
use crate::constants::DEFAULT_PREFIX;
use crate::database::models::Server;
use crate::discord::sanitizing::SanitizeDiscordMarkdown;
use crate::extras::Extras;
use crate::framework::commands::arguments::{Arg, Argument, GreedyString, ParseArguments};
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::framework::commands::{Command, CommandError};
use crate::groups::servers::permissions::{GuildOnlyPermission, ServerModeratorPermission};
use crate::state::State;
#[derive(Debug)]
pub struct PrefixCommand;
#[async_trait]
impl Command<State> for PrefixCommand {
impl Command<State, Extras> for PrefixCommand {
fn name(&self) -> &'static str {
"prefix"
}
@@ -37,12 +36,19 @@ impl Command<State> for PrefixCommand {
}]
}
fn permissions(&self) -> Vec<Box<dyn Permission<State, Extras> + Send + Sync + 'static>> {
vec![
Box::new(GuildOnlyPermission),
Box::new(ServerModeratorPermission),
]
}
async fn execute(
&self,
ctx: CommandContext<'_, State>,
ctx: CommandContext<'_, State, Extras>,
args: &str,
) -> Result<(), CommandError> {
let prefix: GreedyString = ParseArguments::parse(args).unwrap();
let Arg(prefix) = Arg::<GreedyString>::parse(args, &ctx).await.unwrap();
let mut prefix = prefix.trim();
let mut server = Server::get_or_create_by_id(
@@ -54,18 +60,14 @@ impl Command<State> for PrefixCommand {
&ctx.rt.http,
)
.await
.inspect_err(|e| log::error!("Failed to get or create server: {e}"))
.map_err(|_| CommandError::DatabaseQueryFailed)?;
.inspect_err(|e| log::error!("Failed to get or create server: {e}"))?;
if prefix.is_empty() {
prefix = DEFAULT_PREFIX;
}
server.prefix = prefix.to_string();
server
.upsert(&ctx.rt.state.db)
.await
.map_err(|_| CommandError::DatabaseQueryFailed)?;
server.upsert(&ctx.rt.state.db).await?;
ctx.send()
.content(format!(
@@ -73,10 +75,7 @@ impl Command<State> for PrefixCommand {
prefix.sanitize(false)
))
.await
.map_err(|e| {
log::error!("Failed to send prefix update message: {e}");
CommandError::MessageSendingFailed
})?;
.inspect_err(|e| log::error!("Failed to send prefix update message: {e}"))?;
Ok(())
}
+24 -15
View File
@@ -5,24 +5,25 @@ use std::sync::Arc;
use async_trait::async_trait;
use twilight_model::gateway::payload::incoming::{GuildCreate, GuildDelete, GuildUpdate};
use crate::{
database::models::Server,
framework::{
events::traits::{
EventResult, OnServerCreateHandler, OnServerDeleteHandler, OnServerUpdateHandler,
},
runtime::Runtime,
},
state::State,
use crate::database::models::Server;
use crate::extras::Extras;
use crate::framework::events::traits::{
EventResult, OnServerCreateHandler, OnServerDeleteHandler, OnServerUpdateHandler,
};
use crate::framework::runtime::Runtime;
use crate::state::State;
/// Adds servers to the DB when they get created.
#[derive(Debug)]
pub struct ServerCreateHandler;
#[async_trait]
impl OnServerCreateHandler<State> for ServerCreateHandler {
async fn on_server_create(&self, event: &GuildCreate, rt: Arc<Runtime<State>>) -> EventResult {
impl OnServerCreateHandler<State, Extras> for ServerCreateHandler {
async fn on_server_create(
&self,
event: &GuildCreate,
rt: Arc<Runtime<State, Extras>>,
) -> EventResult {
let server = match event {
GuildCreate::Available(guild) => Server::from(guild.clone()),
GuildCreate::Unavailable(_) => {
@@ -51,8 +52,12 @@ impl OnServerCreateHandler<State> for ServerCreateHandler {
pub struct ServerUpdateHandler;
#[async_trait]
impl OnServerUpdateHandler<State> for ServerUpdateHandler {
async fn on_server_update(&self, event: &GuildUpdate, rt: Arc<Runtime<State>>) -> EventResult {
impl OnServerUpdateHandler<State, Extras> for ServerUpdateHandler {
async fn on_server_update(
&self,
event: &GuildUpdate,
rt: Arc<Runtime<State, Extras>>,
) -> EventResult {
let mut server = match Server::get_by_id(event.0.id.get(), &rt.state.db)
.await
.inspect_err(|e| {
@@ -83,8 +88,12 @@ impl OnServerUpdateHandler<State> for ServerUpdateHandler {
pub struct ServerDeleteHandler;
#[async_trait]
impl OnServerDeleteHandler<State> for ServerDeleteHandler {
async fn on_server_delete(&self, event: &GuildDelete, rt: Arc<Runtime<State>>) -> EventResult {
impl OnServerDeleteHandler<State, Extras> for ServerDeleteHandler {
async fn on_server_delete(
&self,
event: &GuildDelete,
rt: Arc<Runtime<State, Extras>>,
) -> EventResult {
Server::delete_by_id(event.id.get(), &rt.state.db)
.await
.inspect(|_| log::debug!("Deleted server with ID {} because Payphone left", event.id))
+81 -18
View File
@@ -1,17 +1,33 @@
use async_trait::async_trait;
use twilight_model::guild::Permissions;
use twilight_model::id::Id;
use twilight_model::id::marker::RoleMarker;
use twilight_util::permission_calculator::PermissionCalculator;
use crate::{
framework::commands::{CommandError, context::CommandContext, permissions::Permission},
state::State,
};
use crate::extras::Extras;
use crate::framework::commands::CommandError;
use crate::framework::commands::context::CommandContext;
use crate::framework::commands::permissions::Permission;
use crate::state::State;
#[derive(Debug)]
pub struct GuildOnlyPermission;
#[async_trait]
impl Permission<State> for GuildOnlyPermission {
async fn check(&self, ctx: &CommandContext<State>) -> Result<bool, CommandError> {
Ok(ctx.event.guild_id.is_none())
impl Permission<State, Extras> for GuildOnlyPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
Ok(ctx.event.guild_id.is_some())
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("❌ This command can only be used in a server.")
.await?;
Ok(())
}
}
@@ -19,18 +35,65 @@ impl Permission<State> for GuildOnlyPermission {
pub struct ServerModeratorPermission;
#[async_trait]
impl Permission<State> for ServerModeratorPermission {
async fn check(&self, ctx: &CommandContext<State>) -> Result<bool, CommandError> {
let member = ctx
.rt
.http
.guild_member(ctx.event.guild_id.unwrap(), ctx.event.author.id)
.await
.map_err(CommandError::DiscordAPIFailed)?
.model()
.await
.map_err(CommandError::DiscordDeserializationFailed)?;
impl Permission<State, Extras> for ServerModeratorPermission {
async fn check(&self, ctx: &CommandContext<State, Extras>) -> Result<bool, CommandError> {
if let Some(guild_id) = ctx.event.guild_id {
let Some(guild) = ctx.rt.cache.guild(guild_id) else {
log::warn!("Could not get guild for ID {guild_id}!");
return Ok(false);
};
let member = ctx
.rt
.http
.guild_member(guild_id, ctx.event.author.id)
.await?
.model()
.await?;
let Some(everyone_role) = ctx.rt.cache.role(guild_id.cast()) else {
log::warn!("Could not get @everyone role for guild ID {guild_id}!");
return Ok(false);
};
let member_roles: Vec<(Id<RoleMarker>, Permissions)> = member
.roles
.into_iter()
.filter_map(|role_id| {
ctx.rt
.cache
.role(role_id)
.map(|role| (role.id, role.permissions))
})
.collect();
let calculator = PermissionCalculator::new(
guild_id,
ctx.event.author.id,
everyone_role.permissions,
&member_roles,
)
.owner_id(guild.owner_id());
return Ok(calculator
.root()
.contains(Permissions::MANAGE_CHANNELS | Permissions::MANAGE_MESSAGES));
}
// DMs channel, the user has all permissions.
Ok(true)
}
async fn on_handle_denied(
&self,
ctx: &CommandContext<State, Extras>,
) -> Result<(), CommandError> {
ctx.send()
.content("❌ This command can only be run by a server moderator.\n-# 🛈 Moderators must have permission to manage messages and to manage channels.")
.await?;
Ok(())
}
}
-9
View File
@@ -1,9 +0,0 @@
pub mod cli;
pub mod constants;
pub mod database;
pub mod discord;
pub mod framework;
pub mod groups;
pub mod logging;
pub mod state;
pub mod utils;
+2 -1
View File
@@ -39,7 +39,8 @@
use colored::Colorize;
use log::{Level, LevelFilter};
use time::{OffsetDateTime, macros::format_description};
use time::OffsetDateTime;
use time::macros::format_description;
pub struct Logger;
+111 -43
View File
@@ -100,51 +100,60 @@
//! $ cargo run -- docs --open
//! ```
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
path::Path,
process::Command,
sync::mpsc,
};
use std::error::Error;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use async_trait::async_trait;
use axum::{Router, response::Redirect, routing};
use axum::response::Redirect;
use axum::{Router, routing};
use clap::Parser;
use notify::{Event, EventKind, Watcher};
use tokio::net::TcpListener;
use tower_http::services::ServeDir;
use twilight_cache_inmemory::ResourceType;
use twilight_gateway::{Intents, ShardId};
use twilight_model::user::User as TwilightUser;
use crate::{
cli::{Args, Commands},
constants::DEFAULT_PREFIX,
database::models::Server,
framework::{
bot::{Bot, PrefixGetter},
runtime::Runtime,
},
groups::{
about::{commands::HelpCommand, components::HelpGoBackButton},
calls::{
commands::{CallCommand, FriendRequestCommand, HangupCommand, SkipCommand},
events::{CallMessageDeleteHandler, CallMessageEditHandler, CallMessageHandler},
},
gateway::events::{ReadyHandler, ReconnectHandler},
servers::{
commands::PrefixCommand,
events::{ServerCreateHandler, ServerDeleteHandler, ServerUpdateHandler},
},
},
state::State,
use crate::cli::{Args, Commands};
use crate::colors::init_color_fetching_queue_listener;
use crate::constants::{DEFAULT_PREFIX, VERSION};
use crate::database::models::{Server, User};
use crate::extras::Extras;
use crate::framework::bot::{Bot, PrefixGetter};
use crate::framework::commands::extras::ExtrasGetter;
use crate::framework::runtime::Runtime;
use crate::groups::about::commands::{CodeOfConductCommand, DonateCommand, HelpCommand};
use crate::groups::about::components::HelpGoBackButton;
use crate::groups::about::tasks::UpdatePresenceTask;
use crate::groups::calls::commands::{
CallCommand, FriendRequestCommand, HangupCommand, MaskCommand, SkipCommand,
};
use crate::groups::calls::events::{
CallMessageDeleteHandler, CallMessageEditHandler, CallMessageHandler,
};
use crate::groups::gateway::events::{ReadyHandler, ReconnectHandler};
use crate::groups::leveling::commands::LeaderboardCommand;
use crate::groups::leveling::events::MessageLevelingHandler;
use crate::groups::moderation::commands::{BanCommand, IncidentsCommand, ModeratorCommand, RemoteHangupCommand};
use crate::groups::servers::commands::PrefixCommand;
use crate::groups::servers::events::{
ServerCreateHandler, ServerDeleteHandler, ServerUpdateHandler,
};
use crate::state::State;
mod cli;
mod colors;
mod constants;
mod database;
mod discord;
mod extras;
mod framework;
mod groups;
mod logging;
mod redis;
mod state;
mod utils;
@@ -168,6 +177,9 @@ pub async fn main() {
database_username,
database_password,
shard,
redis_urls,
bot_owner_id,
topgg_token,
} => {
start(
token,
@@ -175,6 +187,9 @@ pub async fn main() {
database_username,
database_password,
shard.into(),
redis_urls,
bot_owner_id,
topgg_token,
)
.await;
}
@@ -188,10 +203,10 @@ pub async fn main() {
struct ServerPrefixOrPayphoneMention;
#[async_trait]
impl PrefixGetter<State> for ServerPrefixOrPayphoneMention {
impl PrefixGetter<State, Extras> for ServerPrefixOrPayphoneMention {
async fn get(
&self,
rt: &Runtime<State>,
rt: &Runtime<State, Extras>,
server_id: Option<u64>,
_user_id: Option<u64>,
) -> Vec<String> {
@@ -199,58 +214,111 @@ impl PrefixGetter<State> for ServerPrefixOrPayphoneMention {
let default_prefixes = vec![DEFAULT_PREFIX.to_string(), mention.clone()];
if let Some(server_id) = server_id {
if let Ok(Some(server)) = Server::get_by_id(server_id, &rt.state.db).await {
return vec![server.prefix, mention];
}
if let Some(server_id) = server_id
&& let Ok(Some(server)) = Server::get_by_id(server_id, &rt.state.db).await
{
return vec![server.prefix, mention];
}
default_prefixes
}
}
struct PayphoneExtrasGetter;
#[async_trait]
impl ExtrasGetter<State> for PayphoneExtrasGetter {
type Extras = Extras;
async fn get_extra(
&self,
user: &TwilightUser,
rt: &Runtime<State, Self::Extras>,
) -> Result<Self::Extras, Box<dyn Error>> {
log::trace!("Getting extras!");
let user = User::create_or_update(user.clone(), &rt.state.db, &rt.state.color_queue_sender)
.await?;
Ok(Extras { user })
}
}
/// Starts a Payphone shard.
#[allow(clippy::too_many_arguments)]
async fn start(
token: String,
database_addr: String,
database_username: Option<String>,
database_password: Option<String>,
shard: ShardId,
redis_urls: Vec<String>,
bot_owner_id: u64,
topgg_token: Option<String>,
) {
log::info!("Welcome to Payphone, Nyeki!");
log::info!(
"Payphone is running on version v{}",
env!("CARGO_PKG_VERSION")
);
log::info!("Payphone is running on version v{VERSION}");
let db = database::init(database_addr, database_username, database_password)
.await
.expect("Could not connect to the database!");
log::info!("Database connection established successfully!");
log::info!("Database connection established successfully.");
let state = State { db };
let redis_pool = redis::init(redis_urls).expect("Could not connect to Redis!");
let bot = Bot::new(state, ServerPrefixOrPayphoneMention)
log::info!("Redis connection established successfully.");
let (color_queue_sender, color_queue_receiver) = tokio::sync::mpsc::channel(100);
let state = Arc::new(State {
db,
redis: redis_pool,
bot_owner_id,
color_queue_sender,
});
init_color_fetching_queue_listener(color_queue_receiver, state.clone());
let mut bot = Bot::new(state, ServerPrefixOrPayphoneMention, PayphoneExtrasGetter)
.shard(shard)
.intent(Intents::GUILDS)
.intent(Intents::GUILD_MESSAGES)
.intent(Intents::MESSAGE_CONTENT)
.command(HelpCommand)
.command(CodeOfConductCommand)
.command(DonateCommand)
.command(CallCommand::new())
.command(SkipCommand)
.command(HangupCommand)
.command(FriendRequestCommand)
.command(MaskCommand)
.command(LeaderboardCommand)
.command(PrefixCommand)
.command(ModeratorCommand)
.command(IncidentsCommand)
.command(BanCommand)
.command(RemoteHangupCommand)
.component(HelpGoBackButton)
.cache_resource_type(ResourceType::GUILD)
.cache_resource_type(ResourceType::CHANNEL)
.cache_resource_type(ResourceType::MEMBER)
.cache_resource_type(ResourceType::ROLE)
// .task(EndInactiveCallsTask::new(shard.number(), shard.total()))
.on_ready(ReadyHandler)
.on_reconnect(ReconnectHandler)
.on_message(CallMessageHandler)
.on_message(MessageLevelingHandler)
.on_message_edit(CallMessageEditHandler)
.on_message_delete(CallMessageDeleteHandler)
.on_server_create(ServerCreateHandler)
.on_server_update(ServerUpdateHandler)
.on_server_delete(ServerDeleteHandler);
.on_server_delete(ServerDeleteHandler)
.task(UpdatePresenceTask);
if let Some(topgg_token) = topgg_token {
bot = bot.topgg_token(topgg_token);
}
bot.run(&token).await.expect("Could not run bot!");
}
@@ -268,7 +336,7 @@ async fn docs(bind: SocketAddr, open_on_start: bool) {
.expect("Failed to run `cargo doc`");
tokio::spawn(async {
let (tx, rx) = mpsc::channel::<notify::Result<Event>>();
let (tx, rx) = std::sync::mpsc::channel::<notify::Result<Event>>();
let mut watcher = notify::recommended_watcher(tx).expect("Failed to create watcher");
+6
View File
@@ -0,0 +1,6 @@
use deadpool_redis::Runtime;
use deadpool_redis::cluster::{Config, CreatePoolError, Pool};
pub fn init(urls: Vec<String>) -> Result<Pool, CreatePoolError> {
Config::from_urls(urls).create_pool(Some(Runtime::Tokio1))
}

Some files were not shown because too many files have changed in this diff Show More