-
Notifications
You must be signed in to change notification settings - Fork 0
feat: save group tag in DB on create #70
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,52 @@ | ||
| import z from "zod" | ||
| import { GroupManagement } from "@/lib/group-management" | ||
| import { CommandsCollection } from "@/lib/managed-commands" | ||
| import { fmt } from "@/utils/format" | ||
| import type { Role } from "@/utils/types" | ||
|
|
||
| export const groups = new CommandsCollection<Role>("Groups").createCommand({ | ||
| trigger: "updategroup", | ||
| scope: "private", | ||
| description: "Trigger group info update to the database (eg. title or tag change)", | ||
| args: [ | ||
| { | ||
| key: "chatId", | ||
| optional: false, | ||
| type: z.coerce.number(), | ||
| description: "Chat ID (number, obtained from alternative clients) of the group you want to force update", | ||
| }, | ||
| ], | ||
| permissions: { | ||
| allowedRoles: ["owner", "direttivo"], | ||
| }, | ||
| handler: async ({ context, args }) => { | ||
| const group = await context.api.getChat(args.chatId).catch(() => null) | ||
| if (!group) | ||
| return void context.reply( | ||
| fmt( | ||
| ({ code, n }) => | ||
| n`Group with chatId ${code`${args.chatId}`} does not exists or the bot is not an administrator.` | ||
| ) | ||
| ) | ||
|
|
||
| if (group.type === "private") | ||
| return void context.reply( | ||
| fmt(({ code, n }) => n`Chat with chatId ${code`${args.chatId}`} is a private chat, not a group.`) | ||
| ) | ||
|
|
||
| const res = await GroupManagement.update(group.id, context.from) | ||
| if (res.isErr()) { | ||
| return void context.reply( | ||
| fmt(({ code, n, b, i }) => [b`There was an ERROR`, n`chatId: ${code`${args.chatId}`}`, i`\n${res.error}`], { | ||
| sep: "\n", | ||
| }) | ||
| ) | ||
| } | ||
|
|
||
| await context.reply( | ||
| fmt(({ code, n, b }) => [b`✅ Group Updated`, n`chatId: ${code`${args.chatId}`}`], { | ||
| sep: "\n", | ||
| }) | ||
| ) | ||
| }, | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,161 @@ | ||
| import type { AppRouter } from "@polinetwork/backend" | ||
| import type { TRPCClient } from "@trpc/client" | ||
| import type { Chat, ChatFullInfo } from "grammy/types" | ||
| import type { Chat, ChatFullInfo, User } from "grammy/types" | ||
| import type { Result } from "neverthrow" | ||
|
|
||
| import { err, ok } from "neverthrow" | ||
|
|
||
| import { api } from "@/backend" | ||
| import { logger } from "@/logger" | ||
| import { modules } from "@/modules" | ||
| import { printUsername } from "@/utils/users" | ||
|
|
||
| function stripChatInfo(chat: ChatFullInfo) { | ||
| return { | ||
| id: chat.id, | ||
| title: chat.title, | ||
| tag: chat.username, | ||
| is_forum: chat.is_forum, | ||
| type: chat.type, | ||
| invite_link: chat.invite_link, | ||
| } | ||
| } | ||
|
|
||
| async function errorNoInviteLink(chat: ChatFullInfo, type: "CREATE" | "UPDATE") { | ||
| const reason = "Missing invite_link, probably the bot is not admin or does not have permission to invite via link" | ||
| logger.error({ chat: stripChatInfo(chat), reason }, `[GroupManagement] Cannot ${type} group`) | ||
| await modules.get("tgLogger").groupManagement({ | ||
| type: type === "CREATE" ? "CREATE_FAIL" : "UPDATE_FAIL", | ||
| chat, | ||
| reason, | ||
| }) | ||
| return err(reason) | ||
| } | ||
|
|
||
| async function errorBackend(chat: ChatFullInfo, type: "CREATE" | "UPDATE", fatal: boolean = false) { | ||
| if (fatal) logger.fatal("[GroupManagement] HELP! Sent and recieved chatId do not match") | ||
| const reason = `${fatal ? "FATAL " : ""}There was an error in the backend` | ||
| logger.error({ chat: stripChatInfo(chat), reason }, `[GroupManagement] Cannot ${type} group`) | ||
| await modules.get("tgLogger").groupManagement({ | ||
| type: type === "CREATE" ? "CREATE_FAIL" : "UPDATE_FAIL", | ||
| chat, | ||
| inviteLink: chat.invite_link, | ||
| reason, | ||
| }) | ||
| return err(reason) | ||
| } | ||
|
|
||
| type GroupDB = Parameters<TRPCClient<AppRouter>["tg"]["groups"]["create"]["mutate"]>[0][0] | ||
| export const GroupManagement = { | ||
| async create(chat: ChatFullInfo): Promise<Result<GroupDB, string>> { | ||
| async create(chatId: number, addedBy: User): Promise<Result<GroupDB, string>> { | ||
| const chat = await modules.shared.api.getChat(chatId).catch(() => null) | ||
| if (!chat) { | ||
| const reason = "The bot cannot retrieve chat info, probably it is not an administrator" | ||
| logger.error({ chatId, reason }, "[GroupManagement] Cannot CREATE group") | ||
| await modules.get("tgLogger").exception({ | ||
| type: "GENERIC", | ||
| error: new Error("Cannot execute GroupManagement.create because the bot cannot fetch the chat from API."), | ||
| }) | ||
| return err(reason) | ||
| } | ||
|
|
||
| if (!chat.invite_link) { | ||
| return err(`no invite_link, maybe the user does not have permission to "Invite users via link"`) | ||
| return errorNoInviteLink(chat, "CREATE") | ||
| } | ||
|
|
||
| const newGroup: GroupDB = { telegramId: chat.id, title: chat.title, link: chat.invite_link } | ||
| // chat.username does not start with @ | ||
| const newGroup: GroupDB = { telegramId: chat.id, title: chat.title, link: chat.invite_link, tag: chat.username } | ||
| const res = await api.tg.groups.create.mutate([newGroup]) | ||
| if (!res.length || res[0] !== chat.id) { | ||
| return err(`unknown`) | ||
| return errorBackend(chat, "CREATE", res.length >= 1 && res[0] !== chat.id) | ||
| } | ||
|
|
||
| await modules.get("tgLogger").groupManagement({ type: "CREATE", chat, addedBy, inviteLink: chat.invite_link }) | ||
| logger.info( | ||
| { chat: stripChatInfo(chat), addedBy: printUsername(addedBy) }, | ||
| "[GroupManagement] CREATE group success" | ||
| ) | ||
| return ok(newGroup) | ||
| }, | ||
|
|
||
| async update(chatId: number, requestedBy: User): Promise<Result<GroupDB, string>> { | ||
| const chat = await modules.shared.api.getChat(chatId).catch(() => null) | ||
| if (!chat) { | ||
| const reason = "The bot is not in this group or is not an administrator" | ||
| logger.warn({ chatId, reason }, "[GroupManagement] Cannot UPDATE group") | ||
| return err(reason) | ||
| } | ||
|
|
||
| if (!chat.invite_link) { | ||
| return errorNoInviteLink(chat, "UPDATE") | ||
| } | ||
|
|
||
| const saved = await api.tg.groups.getById.query({ telegramId: chat.id }).catch(() => null) | ||
| if (!saved) { | ||
| const reason = "Group with this chatId does not exist in the database." | ||
| logger.warn({ chat: stripChatInfo(chat), reason }, "[GroupManagement] Cannot UPDATE group") | ||
| return err(reason) | ||
| } | ||
|
|
||
| // chat.username does not start with @ | ||
| const updatedGroup: GroupDB = { telegramId: chat.id, title: chat.title, link: chat.invite_link, tag: chat.username } | ||
| const res = await api.tg.groups.create.mutate([updatedGroup]) | ||
| if (!res.length || res[0] !== chat.id) { | ||
| return errorBackend(chat, "UPDATE", res.length >= 1 && res[0] !== chat.id) | ||
| } | ||
|
|
||
| await modules | ||
| .get("tgLogger") | ||
| .groupManagement({ type: "UPDATE", chat, addedBy: requestedBy, inviteLink: chat.invite_link }) | ||
| logger.info( | ||
| { chat: stripChatInfo(chat), requestedBy: printUsername(requestedBy) }, | ||
| "[GroupManagement] UPDATE group success" | ||
| ) | ||
| return ok(updatedGroup) | ||
| }, | ||
|
|
||
| async delete(chat: Chat): Promise<Result<void, string>> { | ||
| const deleted = await api.tg.groups.delete.mutate({ telegramId: chat.id }) | ||
| if (!deleted) return err("it probably wasn't there") | ||
| if (!deleted) { | ||
| const reason = "Group with this chatId does not exist in the database." | ||
| logger.warn({ chat, reason }, "[GroupManagement] Cannot DELETE group") | ||
| return err(reason) | ||
| } | ||
|
|
||
| await modules.get("tgLogger").groupManagement({ type: "DELETE", chat }) | ||
| logger.info({ chat }, "[GroupManagement] DELETE group success") | ||
| return ok() | ||
| }, | ||
|
|
||
| async checkAdderPermission(chat: Chat, addedBy: User): Promise<boolean> { | ||
| const { allowed } = await api.tg.permissions.canAddBot.query({ userId: addedBy.id }) | ||
| if (allowed) { | ||
| logger.debug( | ||
| { chat, addedBy: printUsername(addedBy), allowed }, | ||
| `[GroupManagement] checkAdderPermission result: ALLOWED` | ||
| ) | ||
| return true | ||
| } | ||
|
|
||
| const left = await modules.shared.api.leaveChat(chat.id).catch(() => false) | ||
| if (!left) { | ||
| await modules.get("tgLogger").groupManagement({ | ||
| type: "LEAVE_FAIL", | ||
| chat, | ||
| addedBy, | ||
| }) | ||
| logger.error( | ||
| { chat, addedBy: printUsername(addedBy), allowed, left }, | ||
| `[GroupManagement] checkAdderPermission result: DENIED. Cannot leave unauthorized group` | ||
| ) | ||
| return false | ||
| } | ||
|
|
||
| await modules.get("tgLogger").groupManagement({ type: "LEAVE", chat, addedBy: addedBy }) | ||
| logger.warn( | ||
| { chat, addedBy: printUsername(addedBy), allowed, left }, | ||
| `[GroupManagement] checkAdderPermission result: DENIED. LEFT unauthorized group` | ||
| ) | ||
| return false | ||
| }, | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.