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 Chat 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 Chat 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 simplifies dealing with chat members by offering strongly-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 and my. Both of them specify the old and new status of the user.
myupdates 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 chatupdates 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._member
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 and new are narrowed down accordingly.
import { API_CONSTANTS, Bot } from "grammy";
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!`);
},
);
// 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;
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!");
});
// 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");
});
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"],
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { API_CONSTANTS, Bot } from "grammy";
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!`);
},
);
// 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;
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!");
});
// 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");
});
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"],
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import { API_CONSTANTS, Bot } from "https://deno.land/x/grammy@v1.41.1/mod.ts";
import {
chatMemberFilter,
myChatMemberFilter,
} from "https://deno.land/x/grammy_chat_members/mod.ts";
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!`);
},
);
// 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;
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!");
});
// 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");
});
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"],
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
Filters include the regular statuses (owner, administrator, member, restricted, left, kicked) and some additional ones for convenience:
restricted: a restricted member of the chat_in restricted: not a member of the chat, has restrictions_out 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:
You can create your custom groupings of chat member types by passing an array instead of a string:
groups.filter(
chatMemberFilter(["restricted", "kicked"], ["free", "left"]),
async (ctx) => {
const from = ctx.from;
const { status: oldStatus, user } = ctx.chatMember.old_chat_member;
const lifted = oldStatus === "kicked" ? "ban" : "restrictions";
await ctx.reply(
`${from.first_name} lifted ${lifted} from ${user.first_name}`,
);
},
);2
3
4
5
6
7
8
9
10
11
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 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.
const groups = bot.chatType(["group", "supergroup"]);
groups.on("chat_member", async (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
await 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}!`);
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
Status Checking Utility
The chat 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 narrows the type of the passed variable.
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");
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
Hydrating Chat Member Objects
You can further improve your development experience by using the hydration API transformer. This transformer will apply to calls to get and get, adding a convenient is method to the returned Chat objects.
type MyContext = HydrateChatMemberFlavor<Context>;
type MyApi = HydrateChatMemberApiFlavor<Api>;
const bot = new Bot<MyContext, MyApi>("");
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"
// ...
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Storing Chat Members
You can use a valid grammY storage adapter or an instance of any class that implements the Storage interface.
Please note that as per the official Telegram docs, your bot needs to specify the chat update in the allowed array, as shown in the example below. This means you also need to specify any other events you’d like to receive.
import { API_CONSTANTS, Bot, type Context, MemorySessionStorage } from "grammy";
import { type ChatMember } from "grammy/types";
import { chatMembers, type ChatMembersFlavor } from "@grammyjs/chat-members";
type MyContext = Context & ChatMembersFlavor;
const adapter = new MemorySessionStorage<ChatMember>();
const bot = new Bot<MyContext>("");
bot.use(chatMembers(adapter));
bot.start({
// Make sure to specify the desired update types.
allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"],
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { API_CONSTANTS, Bot, MemorySessionStorage } from "grammy";
import { chatMembers } from "@grammyjs/chat-members";
const adapter = new MemorySessionStorage();
const bot = new Bot("");
bot.use(chatMembers(adapter));
bot.start({
// Make sure to specify the desired update types.
allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"],
});2
3
4
5
6
7
8
9
10
11
12
13
import {
API_CONSTANTS,
Bot,
type Context,
MemorySessionStorage,
} from "https://deno.land/x/grammy@v1.41.1/mod.ts";
import { type ChatMember } from "https://deno.land/x/grammy@v1.41.1/types.ts";
import {
chatMembers,
type ChatMembersFlavor,
} from "https://deno.land/x/grammy_chat_members/mod.ts";
type MyContext = Context & ChatMembersFlavor;
const adapter = new MemorySessionStorage<ChatMember>();
const bot = new Bot<MyContext>("");
bot.use(chatMembers(adapter));
bot.start({
// Make sure to specify the desired update types.
allowed_updates: [...API_CONSTANTS.DEFAULT_UPDATE_TYPES, "chat_member"],
});2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Reading Chat Members
This plugin also adds a new ctx function that will check the storage for information about a chat member before querying Telegram for it. If the chat member exists in the storage, it will be returned. Otherwise, ctx will be called and the result will be saved to the storage, making subsequent calls faster and removing the need to call Telegram again for that user and chat in the future.
Here’s an example:
bot.on("message", async (ctx) => {
const chatMember = await ctx.chatMembers.getChatMember();
return ctx.reply(
`Hello, ${chatMember.user.first_name}! I see you are a ${chatMember.status} of this chat!`,
);
});2
3
4
5
6
7
This function accepts the following optional parameters:
chat:Id - Default:
ctx.chat .id - The chat identifier
- Default:
user:Id - Default:
ctx.from .id - The user identifier
- Default:
You can pass them like so:
bot.on("message", async (ctx) => {
const chatMember = await ctx.chatMembers.getChatMember(
ctx.chat.id,
ctx.from.id,
);
return ctx.reply(
`Hello, ${chatMember.user.first_name}! I see you are a ${chatMember.status} of this chat!`,
);
});2
3
4
5
6
7
8
9
Please notice that, if you don’t provide a chat identifier and there’s no chat property inside the context (for example, on inline query updates), this will throw an error. The same will happen if there’s no ctx in the context.
Aggressive Storage
The enable config option will install middleware to cache chat members without depending on the chat event. For every update, the middleware checks if ctx and ctx exist. If they both do, it then proceeds to call ctx to add the chat member information to the storage in case it doesn’t exist.
Please note that this means the storage will be called for every update, which may be a lot, depending on how many updates your bot receives. This has the potential to impact the performance of your bot drastically. Only use this if you really know what you’re doing and are okay with the risks and consequences.