From 4b099fba41e7ed56016a56d7f7aceb7082c0264c Mon Sep 17 00:00:00 2001 From: bodqhrohro Date: Sun, 8 Dec 2019 15:58:17 +0200 Subject: [PATCH] Add /kick command --- telegram/commands.go | 58 +++++++++++++++++++++++++++++++++----------- 1 file changed, 44 insertions(+), 14 deletions(-) diff --git a/telegram/commands.go b/telegram/commands.go index 5f02c26..26f6b0d 100644 --- a/telegram/commands.go +++ b/telegram/commands.go @@ -112,6 +112,26 @@ func parseCommand(cmdline string) (string, []string) { return bodyFields[0][1:], bodyFields[1:] } +func (c *Client) usernameOrIdToId(username string) (int32, error) { + userID, err := strconv.ParseInt(username, 10, 32) + // couldn't parse the id, try to lookup as a username + if err != nil { + chat, err := c.client.SearchPublicChat(&client.SearchPublicChatRequest{ + Username: username, + }) + if err != nil { + return 0, err + } + + userID = chat.Id + if userID <= 0 || userID > math.MaxInt32 { + return 0, errors.New("Not a user") + } + } + + return int32(userID), nil +} + // ProcessTransportCommand executes a command sent directly to the component // and returns a response func (c *Client) ProcessTransportCommand(cmdline string) string { @@ -451,25 +471,35 @@ func (c *Client) ProcessChatCommand(chatID int64, cmdline string) (string, bool) } if chatID < 0 { - userID, err := strconv.ParseInt(args[0], 10, 32) - // couldn't parse the id, try to lookup as a username + userID, err := c.usernameOrIdToId(args[0]) if err != nil { - chat, err := c.client.SearchPublicChat(&client.SearchPublicChatRequest{ - Username: args[0], - }) - if err != nil { - return err.Error(), true - } - - userID = chat.Id - if userID <= 0 || userID > math.MaxInt32 { - return "Not a user", true - } + return err.Error(), true } _, err = c.client.AddChatMember(&client.AddChatMemberRequest{ ChatId: chatID, - UserId: int32(userID), + UserId: userID, + }) + if err != nil { + return err.Error(), true + } + } + // kick @username from current group chat + case "kick": + if len(args) < 1 { + return notEnoughArguments, true + } + + if chatID < 0 { + userID, err := c.usernameOrIdToId(args[0]) + if err != nil { + return err.Error(), true + } + + _, err = c.client.SetChatMemberStatus(&client.SetChatMemberStatusRequest{ + ChatId: chatID, + UserId: userID, + Status: &client.ChatMemberStatusLeft{}, }) if err != nil { return err.Error(), true