From e4b74e16b4a45020cb2d49e3499f97b3d78ce28f Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Wed, 22 Jan 2025 22:24:15 +0100 Subject: [PATCH 1/9] Updated documentation for chat-members plugin, adding new sections about chat member filters --- site/docs/plugins/chat-members.md | 222 +++++++++++++++++++++++++++++- 1 file changed, 217 insertions(+), 5 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index b0460b24b..7755b817e 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -5,18 +5,230 @@ next: false # Chat Members Plugin (`chat-members`) -Automatically store information about users in a chat and retrieve it easily. -Track group and channel members, and list them. +This plugin makes it easy to work with `ChatMember` objects, by offering a convenient way to listen for changes in the form of custom filters, and by storing and updating the objects. ## Introduction -In many situations, it is necessary for a bot to have information about all the users of a given chat. -Currently, though, the Telegram Bot API exposes no method that allows us to retrieve this information. +Working with `ChatMember` objects from the Telegram Bot API can sometimes be cumbersome, there are several different statuses that are often interchangeable in most applications, as well as a restricted status that can represent both members of the group and restricted users that are not in the group. -This plugin comes to the rescue: automatically listening to `chat_member` events and storing all `ChatMember` objects. +This plugin aims to simplify dealing with chat members, by offering fully typed filters for chat member updates. ## Usage +### Chat member filters + +You can listen for two kinds of updates regarding chat members using a Telegram bot: `chat_member` and `my_chat_member`, +both of them specify the old and new status of the user. + +- `my_chat_member` updates are received by your bot by default and they inform you about the status of the bot being updated in any chat, as well as users blocking the bot; +- `chat_member` updates are only received if you specifically include them in the list of allowed updates, they notify about any status changes for users in chats **where your bot is admin**. + +Instead of manually filtering the old and new status, chat member filters do this automatically for you, allowing you to react to every type of transition you're interested in. +Within the handler, types of `old_chat_member` and `new_chat_member` are updated accordingly. + +::: code-group + +```ts [TypeScript] +import { API_CONSTANTS, Bot } from "grammy"; +import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; + +const bot = new Bot(process.env.BOT_TOKEN!); +const groups = bot.chatType(["group", "supergroup"]); + +groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { + await ctx.reply("Hello, thank you for adding me to the group!"); +}); + +groups.filter(myChatMemberFilter("out", "admin"), async (ctx) => { + await ctx.reply("Hello, thank you for adding me to the group as admin!"); +}); + +groups.filter(myChatMemberFilter("regular", "admin"), async (ctx) => { + await ctx.reply("I was promoted to admin!"); +}); + +groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { + await ctx.reply("I am no longer admin"); +}); + +groups.filter(chatMemberFilter("out", "in"), async (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); +}); + +bot.start({ + // Make sure to specify the desired update types + allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], +}); +``` + +```js [JavaScript] +import { API_CONSTANTS, Bot } from "grammy"; +import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; + +const bot = new Bot(process.env.BOT_TOKEN); +const groups = bot.chatType(["group", "supergroup"]); + +groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { + await ctx.reply("Hello, thank you for adding me to the group!"); +}); + +groups.filter(myChatMemberFilter("out", "admin"), async (ctx) => { + await ctx.reply("Hello, thank you for adding me to the group as admin!"); +}); + +groups.filter(myChatMemberFilter("regular", "admin"), async (ctx) => { + await ctx.reply("I was promoted to admin!"); +}); + +groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { + await ctx.reply("I am no longer admin"); +}); + +groups.filter(chatMemberFilter("out", "in"), async (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); +}); + +bot.start({ + // Make sure to specify the desired update types + allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], +}); +``` + +```ts [Deno] +import { API_CONSTANTS, Bot } from "https://deno.land/x/grammy/mod.ts"; +import { + chatMemberFilter, + myChatMemberFilter, +} from "https://deno.land/x/grammy_chat_members/mod.ts"; + +const bot = new Bot(Deno.env.get("BOT_TOKEN")!); +const groups = bot.chatType(["group", "supergroup"]); + +groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { + await ctx.reply("Hello, thank you for adding me to the group!"); +}); + +groups.filter(myChatMemberFilter("out", "admin"), async (ctx) => { + await ctx.reply("Hello, thank you for adding me to the group as admin!"); +}); + +groups.filter(myChatMemberFilter("regular", "admin"), async (ctx) => { + await ctx.reply("I was promoted to admin!"); +}); + +groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { + await ctx.reply("I am no longer admin"); +}); + +groups.filter(chatMemberFilter("out", "in"), async (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); +}); + +bot.start({ + // Make sure to specify the desired update types + allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], +}); +``` + +::: + +Filters include the regular Telegram statuses (owner, administrator, member, restricted, left, kicked) and some additional ones for convenience: + +- `restricted_in`: a member of the chat with restrictions; +- `restricted_out`: not a member of the chat, has restrictions; +- `in`: a member of the chat (administrator, creator, member, restricted_in); +- `out`: not a member of the chat (left, kicked, restricted_out); +- `free`: a member of the chat that isn't restricted (administrator, creator, member); +- `admin`: an admin of the chat (administrator, creator); +- `regular`: a non-admin member of the chat (member, restricted_in). + +You can create your custom groupings of chat member types by passing an array instead of a string: + +```typescript +groups.filter( + chatMemberFilter(["restricted", "kicked"], ["free", "left"]), + async (ctx) => { + const from = ctx.from; + const { status: oldStatus, user } = ctx.chatMember.old_chat_member; + await ctx.reply( + `${from.first_name} lifted ` + + `${oldStatus === "kicked" ? "ban" : "restrictions"} ` + + `from ${user.first_name}`, + ); + }, +); +``` + +#### Example usage + +The best way to use the filters is to pick a set of relevant statuses, for example 'out', 'regular' and 'admin', then +make a table of the transitions between them: + +| ↱ | Out | Regular | Admin | +| ----------- | ----------- | -------------------- | ------------------- | +| **Out** | ban-changed | join | join-and-promoted | +| **Regular** | exit | restrictions-changed | promoted | +| **Admin** | exit | demoted | permissions-changed | + +Assign a listener to all the transitions that are relevant to your use-case. + +Combine these filters with `bot.chatType` to only listen for transitions for a specific type of chat. Add a middleware to listen to all updates as a way to perform common operations (like updating your database) before handing off control to a specific handler. + +```typescript +const groups = bot.chatType(["group", "supergroup"]); + +groups.on("chat_member", (ctx, next) => { + // ran on all updates of type chat_member + const { + old_chat_member: { status: oldStatus }, + new_chat_member: { user, status }, + from, + chat, + } = ctx.chatMember; + console.log( + `In group ${chat.id} user ${from.id} changed status of ${user.id}:`, + `${oldStatus} -> ${status}`, + ); + + // update database data here + + return next(); +}); + +// specific handlers + +groups.filter(chatMemberFilter("out", "in"), async (ctx, next) => { + const { new_chat_member: { user } } = ctx.chatMember; + await ctx.reply(`Welcome ${user.first_name}!`); +}); +``` + +### Status checking utility + +The `chatMemberIs` utility function can be useful whenever you want to use filtering logic within a handler. +It takes as input any of the regular and custom statuses (or an array of them) and updates the type of the passed variable. + +```ts +bot.callbackQuery("foo", async (ctx) => { + const chatMember = await ctx.getChatMember(ctx.from.id); + + if (!chatMemberIs(chatMember, "free")) { + chatMember.status; // "restricted" | "left" | "kicked" + await ctx.answerCallbackQuery({ + show_alert: true, + text: "You don't have permission to do this!", + }); + return; + } + + chatMember.status; // "creator" | "administrator" | "member" + await ctx.answerCallbackQuery("bar"); +}); +``` + ### Storing Chat Members You can use a valid grammY [storage adapter](./session#known-storage-adapters) or an instance of any class that implements the [`StorageAdapter`](/ref/core/storageadapter) interface. From 639036a0826a8a2a39916157730f2924f759a255 Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Fri, 24 Jan 2025 12:32:38 +0100 Subject: [PATCH 2/9] Improve documentation of chat-members based on suggestions --- site/docs/plugins/chat-members.md | 63 ++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index 7755b817e..9c8fc148e 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -5,26 +5,29 @@ next: false # Chat Members Plugin (`chat-members`) +Telegram doesn't offer a method in the Bot API to retrieve the members of a chat, you have to keep track of them yourself. This plugin makes it easy to work with `ChatMember` objects, by offering a convenient way to listen for changes in the form of custom filters, and by storing and updating the objects. ## Introduction -Working with `ChatMember` objects from the Telegram Bot API can sometimes be cumbersome, there are several different statuses that are often interchangeable in most applications, as well as a restricted status that can represent both members of the group and restricted users that are not in the group. +Working with `ChatMember` objects from the Telegram Bot API can sometimes be cumbersome. +There are several different statuses that are often interchangeable in most applications. +In addition, the restricted status is ambiguous because it can represent both members of the group and restricted users that are not in the group. -This plugin aims to simplify dealing with chat members, by offering fully typed filters for chat member updates. +This plugin simplifies dealing with chat members by offering fully typed filters for chat member updates. ## Usage -### Chat member filters +### Chat Member Filters -You can listen for two kinds of updates regarding chat members using a Telegram bot: `chat_member` and `my_chat_member`, -both of them specify the old and new status of the user. +You can listen for two kinds of updates regarding chat members using a Telegram bot: `chat_member` and `my_chat_member`. +Both of them specify the old and new status of the user. - `my_chat_member` updates are received by your bot by default and they inform you about the status of the bot being updated in any chat, as well as users blocking the bot; -- `chat_member` updates are only received if you specifically include them in the list of allowed updates, they notify about any status changes for users in chats **where your bot is admin**. +- `chat_member` updates are only received if you explicitly include them in the list of allowed updates, they notify about any status changes for users in chats **where your bot is admin**. Instead of manually filtering the old and new status, chat member filters do this automatically for you, allowing you to react to every type of transition you're interested in. -Within the handler, types of `old_chat_member` and `new_chat_member` are updated accordingly. +Within the handler, the types of `old_chat_member` and `new_chat_member` are narrowed down accordingly. ::: code-group @@ -32,32 +35,37 @@ Within the handler, types of `old_chat_member` and `new_chat_member` are updated import { API_CONSTANTS, Bot } from "grammy"; import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; -const bot = new Bot(process.env.BOT_TOKEN!); +const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); +// Listen for updates where the bot is added to a group as a regular user. groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group!"); }); +// Listen for updates where the bot is added to a group as an admin. groups.filter(myChatMemberFilter("out", "admin"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group as admin!"); }); +// Listen for updates where the bot is promoted to admin. groups.filter(myChatMemberFilter("regular", "admin"), async (ctx) => { await ctx.reply("I was promoted to admin!"); }); +// Listen for updates where the bot is demoted to a regular user. groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { await ctx.reply("I am no longer admin"); }); +// Listen for updates where a user joins a group where your bot is admin. groups.filter(chatMemberFilter("out", "in"), async (ctx) => { const user = ctx.chatMember.new_chat_member.user; await ctx.reply(`Welcome ${user.first_name} to the group!`); }); bot.start({ - // Make sure to specify the desired update types + // Make sure to specify the desired update types. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` @@ -66,32 +74,37 @@ bot.start({ import { API_CONSTANTS, Bot } from "grammy"; import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; -const bot = new Bot(process.env.BOT_TOKEN); +const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); +// Listen for updates where the bot is added to a group as a regular user. groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group!"); }); +// Listen for updates where the bot is added to a group as an admin. groups.filter(myChatMemberFilter("out", "admin"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group as admin!"); }); +// Listen for updates where the bot is promoted to admin. groups.filter(myChatMemberFilter("regular", "admin"), async (ctx) => { await ctx.reply("I was promoted to admin!"); }); +// Listen for updates where the bot is demoted to a regular user. groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { await ctx.reply("I am no longer admin"); }); +// Listen for updates where a user joins a group where your bot is admin. groups.filter(chatMemberFilter("out", "in"), async (ctx) => { const user = ctx.chatMember.new_chat_member.user; await ctx.reply(`Welcome ${user.first_name} to the group!`); }); bot.start({ - // Make sure to specify the desired update types + // Make sure to specify the desired update types. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` @@ -103,32 +116,37 @@ import { myChatMemberFilter, } from "https://deno.land/x/grammy_chat_members/mod.ts"; -const bot = new Bot(Deno.env.get("BOT_TOKEN")!); +const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); +// Listen for updates where the bot is added to a group as a regular user. groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group!"); }); +// Listen for updates where the bot is added to a group as an admin. groups.filter(myChatMemberFilter("out", "admin"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group as admin!"); }); +// Listen for updates where the bot is promoted to admin. groups.filter(myChatMemberFilter("regular", "admin"), async (ctx) => { await ctx.reply("I was promoted to admin!"); }); +// Listen for updates where the bot is demoted to a regular user. groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { await ctx.reply("I am no longer admin"); }); +// Listen for updates where a user joins a group where your bot is admin. groups.filter(chatMemberFilter("out", "in"), async (ctx) => { const user = ctx.chatMember.new_chat_member.user; await ctx.reply(`Welcome ${user.first_name} to the group!`); }); bot.start({ - // Make sure to specify the desired update types + // Make sure to specify the desired update types. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` @@ -162,7 +180,7 @@ groups.filter( ); ``` -#### Example usage +#### Example Usage The best way to use the filters is to pick a set of relevant statuses, for example 'out', 'regular' and 'admin', then make a table of the transitions between them: @@ -175,12 +193,13 @@ make a table of the transitions between them: Assign a listener to all the transitions that are relevant to your use-case. -Combine these filters with `bot.chatType` to only listen for transitions for a specific type of chat. Add a middleware to listen to all updates as a way to perform common operations (like updating your database) before handing off control to a specific handler. +Combine these filters with `bot.chatType` to only listen for transitions for a specific type of chat. +Add a middleware to listen to all updates as a way to perform common operations (like updating your database) before handing off control to a specific handler. ```typescript const groups = bot.chatType(["group", "supergroup"]); -groups.on("chat_member", (ctx, next) => { +groups.on("chat_member", async (ctx, next) => { // ran on all updates of type chat_member const { old_chat_member: { status: oldStatus }, @@ -195,7 +214,7 @@ groups.on("chat_member", (ctx, next) => { // update database data here - return next(); + await next(); }); // specific handlers @@ -206,10 +225,10 @@ groups.filter(chatMemberFilter("out", "in"), async (ctx, next) => { }); ``` -### Status checking utility +### Status Checking Utility The `chatMemberIs` utility function can be useful whenever you want to use filtering logic within a handler. -It takes as input any of the regular and custom statuses (or an array of them) and updates the type of the passed variable. +It takes as input any of the regular and custom statuses (or an array of them), and updates the type of the passed variable. ```ts bot.callbackQuery("foo", async (ctx) => { @@ -252,7 +271,7 @@ const bot = new Bot(""); bot.use(chatMembers(adapter)); bot.start({ - // Make sure to specify the desired update types + // Make sure to specify the desired update types. allowed_updates: ["chat_member", "message"], }); ``` @@ -268,7 +287,7 @@ const bot = new Bot(""); bot.use(chatMembers(adapter)); bot.start({ - // Make sure to specify the desired update types + // Make sure to specify the desired update types. allowed_updates: ["chat_member", "message"], }); ``` @@ -294,7 +313,7 @@ const bot = new Bot(""); bot.use(chatMembers(adapter)); bot.start({ - // Make sure to specify the desired update types + // Make sure to specify the desired update types. allowed_updates: ["chat_member", "message"], }); ``` From 7032e84bdfb5382e40fd0d93b7138d6e1e2fbce1 Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Fri, 24 Jan 2025 13:02:08 +0100 Subject: [PATCH 3/9] Add diagram to chat-members plugin, showing the statuses corresponding to each query --- site/docs/plugins/chat-members.md | 4 ++++ site/docs/public/images/chat-members-statuses.svg | 1 + 2 files changed, 5 insertions(+) create mode 100644 site/docs/public/images/chat-members-statuses.svg diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index 9c8fc148e..cb0ce8613 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -163,6 +163,10 @@ Filters include the regular Telegram statuses (owner, administrator, member, res - `admin`: an admin of the chat (administrator, creator); - `regular`: a non-admin member of the chat (member, restricted_in). +To summarize, here is a diagram showing what each query corresponds to: + +![Diagram showing the statuses corresponding to each query.](/images/chat-members-statuses.svg) + You can create your custom groupings of chat member types by passing an array instead of a string: ```typescript diff --git a/site/docs/public/images/chat-members-statuses.svg b/site/docs/public/images/chat-members-statuses.svg new file mode 100644 index 000000000..ed8b5e7c2 --- /dev/null +++ b/site/docs/public/images/chat-members-statuses.svg @@ -0,0 +1 @@ +inoutadminregularleftkickedrestricted_outadministratorcreatorrestricted_inmemberfree \ No newline at end of file From 8abdf8e4dbc5908682c27a66584ff224a59d1b49 Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Thu, 6 Feb 2025 16:18:43 +0100 Subject: [PATCH 4/9] Updated chat-members documentation, adding section about hydration --- site/docs/plugins/chat-members.md | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index cb0ce8613..b30ef54d4 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -232,7 +232,7 @@ groups.filter(chatMemberFilter("out", "in"), async (ctx, next) => { ### Status Checking Utility The `chatMemberIs` utility function can be useful whenever you want to use filtering logic within a handler. -It takes as input any of the regular and custom statuses (or an array of them), and updates the type of the passed variable. +It takes as input any of the regular and custom statuses (or an array of them), and narrows the type of the passed variable. ```ts bot.callbackQuery("foo", async (ctx) => { @@ -252,6 +252,33 @@ bot.callbackQuery("foo", async (ctx) => { }); ``` +### Hydrate Chat Member + +You can further improve your development experience by using the hydration API transformer. +This transformer will apply to calls to `getChatMember` and `getChatAdministrators`, adding a convenient `is` method to the returned `ChatMember` objects. + +```ts +type MyContext = HydrateChatMemberFlavor; +type MyApi = HydrateChatMemberApiFlavor; + +const bot = new Bot(""); + +bot.api.config.use(hydrateChatMember()); + +bot.command("ban", async (ctx) => { + const author = await ctx.getAuthor(); + + if (!author.is("admin")) { + author.status; // "member" | "restricted" | "left" | "kicked" + await ctx.reply("You don't have permission to do this"); + return; + } + + author.status; // "creator" | "administrator" + // ... +}); +``` + ### Storing Chat Members You can use a valid grammY [storage adapter](./session#known-storage-adapters) or an instance of any class that implements the [`StorageAdapter`](/ref/core/storageadapter) interface. From 808938ce2f2d5b25901de78ab5c09d0fd5db8e8f Mon Sep 17 00:00:00 2001 From: rayz <37779815+rayz1065@users.noreply.github.com> Date: Fri, 14 Feb 2025 10:31:52 +0000 Subject: [PATCH 5/9] Apply suggestions from code review Co-authored-by: KnorpelSenf --- site/docs/plugins/chat-members.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index b30ef54d4..6bb8a1e6e 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -252,9 +252,9 @@ bot.callbackQuery("foo", async (ctx) => { }); ``` -### Hydrate Chat Member +### Hydrating Chat Member Objects -You can further improve your development experience by using the hydration API transformer. +You can further improve your development experience by using the hydration [API transformer](../advanced/transformers). This transformer will apply to calls to `getChatMember` and `getChatAdministrators`, adding a convenient `is` method to the returned `ChatMember` objects. ```ts From aa44ba2db9ba8eea97b6bfa99e856150dfe59dc4 Mon Sep 17 00:00:00 2001 From: rayz <37779815+rayz1065@users.noreply.github.com> Date: Wed, 19 Feb 2025 11:14:40 +0000 Subject: [PATCH 6/9] Apply suggestions from code review Co-authored-by: Roj --- site/docs/plugins/chat-members.md | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index 6bb8a1e6e..c07c32278 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -14,7 +14,7 @@ Working with `ChatMember` objects from the Telegram Bot API can sometimes be cum There are several different statuses that are often interchangeable in most applications. In addition, the restricted status is ambiguous because it can represent both members of the group and restricted users that are not in the group. -This plugin simplifies dealing with chat members by offering fully typed filters for chat member updates. +This plugin simplifies dealing with chat members by offering strongly-typed filters for chat member updates. ## Usage @@ -23,10 +23,10 @@ This plugin simplifies dealing with chat members by offering fully typed filters You can listen for two kinds of updates regarding chat members using a Telegram bot: `chat_member` and `my_chat_member`. Both of them specify the old and new status of the user. -- `my_chat_member` updates are received by your bot by default and they inform you about the status of the bot being updated in any chat, as well as users blocking the bot; -- `chat_member` updates are only received if you explicitly include them in the list of allowed updates, they notify about any status changes for users in chats **where your bot is admin**. +- `my_chat_member` updates are always received by your bot to inform you about the status of the bot being updated in any chat, as well as when users block the bot. +- `chat_member` updates are only received if you explicitly include them in the list of allowed updates, they notify about any status changes for users in chats in which the bot is **admin**. -Instead of manually filtering the old and new status, chat member filters do this automatically for you, allowing you to react to every type of transition you're interested in. +Instead of manually filtering the old and the new statuses, chat member filters do this automatically for you, allowing you to act on any type of transition you're interested in. Within the handler, the types of `old_chat_member` and `new_chat_member` are narrowed down accordingly. ::: code-group @@ -65,7 +65,7 @@ groups.filter(chatMemberFilter("out", "in"), async (ctx) => { }); bot.start({ - // Make sure to specify the desired update types. + // Make sure to include the "chat_member" update type for the above handlers to work. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` @@ -104,7 +104,7 @@ groups.filter(chatMemberFilter("out", "in"), async (ctx) => { }); bot.start({ - // Make sure to specify the desired update types. + // Make sure to include the "chat_member" update type for the above handlers to work. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` @@ -146,22 +146,22 @@ groups.filter(chatMemberFilter("out", "in"), async (ctx) => { }); bot.start({ - // Make sure to specify the desired update types. + // Make sure to include the "chat_member" update type for the above handlers to work. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` ::: -Filters include the regular Telegram statuses (owner, administrator, member, restricted, left, kicked) and some additional ones for convenience: +Filters include the regular statuses (owner, administrator, member, restricted, left, kicked) and some additional ones for convenience: -- `restricted_in`: a member of the chat with restrictions; -- `restricted_out`: not a member of the chat, has restrictions; -- `in`: a member of the chat (administrator, creator, member, restricted_in); -- `out`: not a member of the chat (left, kicked, restricted_out); -- `free`: a member of the chat that isn't restricted (administrator, creator, member); -- `admin`: an admin of the chat (administrator, creator); -- `regular`: a non-admin member of the chat (member, restricted_in). +- `restricted_in`: a restricted member of the chat +- `restricted_out`: not a member of the chat, has restrictions +- `in`: a member of the chat (administrator, creator, member, restricted_in) +- `out`: not a member of the chat (left, kicked, restricted_out) +- `free`: a non-restricted member of the chat (administrator, creator, member) +- `admin`: an admin of the chat (administrator, creator) +- `regular`: a non-admin member of the chat (member, restricted_in) To summarize, here is a diagram showing what each query corresponds to: From 1dec670567429c4b01af508428ebc29cb1844519 Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Wed, 19 Feb 2025 12:21:21 +0100 Subject: [PATCH 7/9] Chat members plugin, include DEFAULT_UPDATE_TYPES where they were missing --- site/docs/plugins/chat-members.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index c07c32278..70d958f4b 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -289,7 +289,7 @@ This means you also need to specify any other events you'd like to receive. ::: code-group ```ts [TypeScript] -import { Bot, type Context, MemorySessionStorage } from "grammy"; +import { API_CONSTANTS, Bot, type Context, MemorySessionStorage } from "grammy"; import { type ChatMember } from "grammy/types"; import { chatMembers, type ChatMembersFlavor } from "@grammyjs/chat-members"; @@ -303,12 +303,12 @@ bot.use(chatMembers(adapter)); bot.start({ // Make sure to specify the desired update types. - allowed_updates: ["chat_member", "message"], + allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` ```js [JavaScript] -import { Bot, MemorySessionStorage } from "grammy"; +import { API_CONSTANTS, Bot, MemorySessionStorage } from "grammy"; import { chatMembers } from "@grammyjs/chat-members"; const adapter = new MemorySessionStorage(); @@ -319,12 +319,13 @@ bot.use(chatMembers(adapter)); bot.start({ // Make sure to specify the desired update types. - allowed_updates: ["chat_member", "message"], + allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` ```ts [Deno] import { + API_CONSTANTS, Bot, type Context, MemorySessionStorage, @@ -345,7 +346,7 @@ bot.use(chatMembers(adapter)); bot.start({ // Make sure to specify the desired update types. - allowed_updates: ["chat_member", "message"], + allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], }); ``` From 69159ff1c1e3f2fa9a98943268d479a91f1f9bc1 Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Wed, 19 Feb 2025 12:51:46 +0100 Subject: [PATCH 8/9] Chat members, added example showcasing filtering without the plugin --- site/docs/plugins/chat-members.md | 96 +++++++++++++++++++++++++------ 1 file changed, 78 insertions(+), 18 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index 70d958f4b..f04118c9b 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -38,6 +38,32 @@ import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); +// WITHOUT this plugin, to react whenever a user joins a group you have to +// manually filter by status, resulting in error-prone, difficult to read code. +groups.on("chat_member").filter( + (ctx) => { + const { old_chat_member: oldMember, new_chat_member: newMember } = + ctx.chatMember; + return ( + (["kicked", "left"].includes(oldMember.status) || + (oldMember.status === "restricted" && !oldMember.is_member)) && + (["administrator", "creator", "member"].includes(newMember.status) || + (newMember.status === "restricted" && newMember.is_member)) + ); + }, + (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); + }, +); + +// This plugin simplifies this greatly and reduces the risk of errors. +// The code below listens to the same events but is much simpler. +groups.filter(chatMemberFilter("out", "in"), async (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); +}); + // Listen for updates where the bot is added to a group as a regular user. groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group!"); @@ -58,12 +84,6 @@ groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { await ctx.reply("I am no longer admin"); }); -// Listen for updates where a user joins a group where your bot is admin. -groups.filter(chatMemberFilter("out", "in"), async (ctx) => { - const user = ctx.chatMember.new_chat_member.user; - await ctx.reply(`Welcome ${user.first_name} to the group!`); -}); - bot.start({ // Make sure to include the "chat_member" update type for the above handlers to work. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], @@ -77,6 +97,32 @@ import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); +// WITHOUT this plugin, to react whenever a user joins a group you have to +// manually filter by status, resulting in error-prone, difficult to read code. +groups.on("chat_member").filter( + (ctx) => { + const { old_chat_member: oldMember, new_chat_member: newMember } = + ctx.chatMember; + return ( + (["kicked", "left"].includes(oldMember.status) || + (oldMember.status === "restricted" && !oldMember.is_member)) && + (["administrator", "creator", "member"].includes(newMember.status) || + (newMember.status === "restricted" && newMember.is_member)) + ); + }, + (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); + }, +); + +// This plugin simplifies this greatly and reduces the risk of errors. +// The code below listens to the same events but is much simpler. +groups.filter(chatMemberFilter("out", "in"), async (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); +}); + // Listen for updates where the bot is added to a group as a regular user. groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group!"); @@ -97,12 +143,6 @@ groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { await ctx.reply("I am no longer admin"); }); -// Listen for updates where a user joins a group where your bot is admin. -groups.filter(chatMemberFilter("out", "in"), async (ctx) => { - const user = ctx.chatMember.new_chat_member.user; - await ctx.reply(`Welcome ${user.first_name} to the group!`); -}); - bot.start({ // Make sure to include the "chat_member" update type for the above handlers to work. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], @@ -119,6 +159,32 @@ import { const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); +// WITHOUT this plugin, to react whenever a user joins a group you have to +// manually filter by status, resulting in error-prone, difficult to read code. +groups.on("chat_member").filter( + (ctx) => { + const { old_chat_member: oldMember, new_chat_member: newMember } = + ctx.chatMember; + return ( + (["kicked", "left"].includes(oldMember.status) || + (oldMember.status === "restricted" && !oldMember.is_member)) && + (["administrator", "creator", "member"].includes(newMember.status) || + (newMember.status === "restricted" && newMember.is_member)) + ); + }, + (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); + }, +); + +// This plugin simplifies this greatly and reduces the risk of errors. +// The code below listens to the same events but is much simpler. +groups.filter(chatMemberFilter("out", "in"), async (ctx) => { + const user = ctx.chatMember.new_chat_member.user; + await ctx.reply(`Welcome ${user.first_name} to the group!`); +}); + // Listen for updates where the bot is added to a group as a regular user. groups.filter(myChatMemberFilter("out", "regular"), async (ctx) => { await ctx.reply("Hello, thank you for adding me to the group!"); @@ -139,12 +205,6 @@ groups.filter(myChatMemberFilter("admin", "regular"), async (ctx) => { await ctx.reply("I am no longer admin"); }); -// Listen for updates where a user joins a group where your bot is admin. -groups.filter(chatMemberFilter("out", "in"), async (ctx) => { - const user = ctx.chatMember.new_chat_member.user; - await ctx.reply(`Welcome ${user.first_name} to the group!`); -}); - bot.start({ // Make sure to include the "chat_member" update type for the above handlers to work. allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"], From 4e9b995db45e9d291e03efac26ba46b8fd86e37f Mon Sep 17 00:00:00 2001 From: rayz1065 Date: Wed, 19 Feb 2025 14:19:30 +0100 Subject: [PATCH 9/9] Chat members, apply suggested rephrasing from code review --- site/docs/plugins/chat-members.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/site/docs/plugins/chat-members.md b/site/docs/plugins/chat-members.md index f04118c9b..604c6de0d 100644 --- a/site/docs/plugins/chat-members.md +++ b/site/docs/plugins/chat-members.md @@ -38,7 +38,7 @@ import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); -// WITHOUT this plugin, to react whenever a user joins a group you have to +// WITHOUT this plugin, to react whenever a user joins a group, you have to // manually filter by status, resulting in error-prone, difficult to read code. groups.on("chat_member").filter( (ctx) => { @@ -57,7 +57,7 @@ groups.on("chat_member").filter( }, ); -// This plugin simplifies this greatly and reduces the risk of errors. +// WITH this plugin, the code is greatly simplified and has a lower risk of errors. // The code below listens to the same events but is much simpler. groups.filter(chatMemberFilter("out", "in"), async (ctx) => { const user = ctx.chatMember.new_chat_member.user; @@ -97,7 +97,7 @@ import { chatMemberFilter, myChatMemberFilter } from "@grammyjs/chat-members"; const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); -// WITHOUT this plugin, to react whenever a user joins a group you have to +// WITHOUT this plugin, to react whenever a user joins a group, you have to // manually filter by status, resulting in error-prone, difficult to read code. groups.on("chat_member").filter( (ctx) => { @@ -116,7 +116,7 @@ groups.on("chat_member").filter( }, ); -// This plugin simplifies this greatly and reduces the risk of errors. +// WITH this plugin, the code is greatly simplified and has a lower risk of errors. // The code below listens to the same events but is much simpler. groups.filter(chatMemberFilter("out", "in"), async (ctx) => { const user = ctx.chatMember.new_chat_member.user; @@ -159,7 +159,7 @@ import { const bot = new Bot(""); const groups = bot.chatType(["group", "supergroup"]); -// WITHOUT this plugin, to react whenever a user joins a group you have to +// WITHOUT this plugin, to react whenever a user joins a group, you have to // manually filter by status, resulting in error-prone, difficult to read code. groups.on("chat_member").filter( (ctx) => { @@ -178,7 +178,7 @@ groups.on("chat_member").filter( }, ); -// This plugin simplifies this greatly and reduces the risk of errors. +// WITH this plugin, the code is greatly simplified and has a lower risk of errors. // The code below listens to the same events but is much simpler. groups.filter(chatMemberFilter("out", "in"), async (ctx) => { const user = ctx.chatMember.new_chat_member.user;