1
1
import { Context , Telegraf } from "telegraf" ;
2
+ import { message } from 'telegraf/filters' ;
2
3
import { IAgentRuntime , elizaLogger } from "@ai16z/eliza" ;
3
4
import { MessageManager } from "./messageManager.ts" ;
4
5
import { getOrCreateRecommenderInBe } from "./getOrCreateRecommenderInBe.ts" ;
@@ -47,11 +48,56 @@ export class TelegramClient {
47
48
this . messageManager . bot = this . bot ;
48
49
}
49
50
51
+ private async isGroupAuthorized ( ctx : Context ) : Promise < boolean > {
52
+ const config = this . runtime . character . clientConfig ?. telegram ;
53
+ if ( ctx . from ?. id === ctx . botInfo ?. id ) {
54
+ return false ;
55
+ }
56
+
57
+ if ( ! config ?. shouldOnlyJoinInAllowedGroups ) {
58
+ return true ;
59
+ }
60
+
61
+ const allowedGroups = config . allowedGroupIds || [ ] ;
62
+ const currentGroupId = ctx . chat . id . toString ( ) ;
63
+
64
+ if ( ! allowedGroups . includes ( currentGroupId ) ) {
65
+ elizaLogger . info ( `Unauthorized group detected: ${ currentGroupId } ` ) ;
66
+ try {
67
+ await ctx . reply ( "Not authorized. Leaving." ) ;
68
+ await ctx . leaveChat ( ) ;
69
+ } catch ( error ) {
70
+ elizaLogger . error ( `Error leaving unauthorized group ${ currentGroupId } :` , error ) ;
71
+ }
72
+ return false ;
73
+ }
74
+
75
+ return true ;
76
+ }
77
+
50
78
private setupMessageHandlers ( ) : void {
51
79
elizaLogger . log ( "Setting up message handler..." ) ;
52
80
81
+ this . bot . on ( message ( 'new_chat_members' ) , async ( ctx ) => {
82
+ try {
83
+ const newMembers = ctx . message . new_chat_members ;
84
+ const isBotAdded = newMembers . some ( member => member . id === ctx . botInfo . id ) ;
85
+
86
+ if ( isBotAdded && ! ( await this . isGroupAuthorized ( ctx ) ) ) {
87
+ return ;
88
+ }
89
+ } catch ( error ) {
90
+ elizaLogger . error ( "Error handling new chat members:" , error ) ;
91
+ }
92
+ } ) ;
93
+
53
94
this . bot . on ( "message" , async ( ctx ) => {
54
95
try {
96
+ // Check group authorization first
97
+ if ( ! ( await this . isGroupAuthorized ( ctx ) ) ) {
98
+ return ;
99
+ }
100
+
55
101
if ( this . tgTrader ) {
56
102
const userId = ctx . from ?. id . toString ( ) ;
57
103
const username =
@@ -76,12 +122,18 @@ export class TelegramClient {
76
122
) ;
77
123
}
78
124
}
125
+
79
126
await this . messageManager . handleMessage ( ctx ) ;
80
127
} catch ( error ) {
81
128
elizaLogger . error ( "❌ Error handling message:" , error ) ;
82
- await ctx . reply (
83
- "An error occurred while processing your message."
84
- ) ;
129
+ // Don't try to reply if we've left the group or been kicked
130
+ if ( error ?. response ?. error_code !== 403 ) {
131
+ try {
132
+ await ctx . reply ( "An error occurred while processing your message." ) ;
133
+ } catch ( replyError ) {
134
+ elizaLogger . error ( "Failed to send error message:" , replyError ) ;
135
+ }
136
+ }
85
137
}
86
138
} ) ;
87
139
0 commit comments