Skip to content

Commit

Permalink
Update 0.2.9.1
Browse files Browse the repository at this point in the history
Rewritten antispam.js spam detection
Added support generally for message events on main.js, added GHbot.onEditedMessage, GHbot.onEditedMessageText
  • Loading branch information
Sp3rick committed Sep 3, 2024
1 parent 523acba commit a823737
Show file tree
Hide file tree
Showing 9 changed files with 269 additions and 110 deletions.
24 changes: 23 additions & 1 deletion GHbot.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/**
* IMPORTANT: README
* If you edit this file don't forget to run `node runDocs.js` before pull request
* In case of errors maybe you wrong something on the JSDocs here
*/

const TelegramBot = require("node-telegram-bot-api");
const { pushUserRequest } = require("./api/tg/SafeTelegram");

Expand Down Expand Up @@ -434,7 +440,23 @@ class LGHInterface {
}

/**
* LGHbot callback event handler
* LGHbot edited_message event handler
* @param {function(LGHMessage, LGHChat, LGHUser): void} handler - handler function
*/
onEditedMessage(handler) {
this.GHbot.on("edited_message", handler);
}

/**
* LGHbot edited_message event handler
* @param {function(LGHMessage, LGHChat, LGHUser): void} handler - handler function
*/
onEditedMessageText(handler) {
this.GHbot.on("edited_message_text", handler);
}

/**
* LGHbot callback_query event handler
* @param {function(LGHCallback, LGHChat, LGHUser): void} handler - handler function
*/
onCallback(handler) {
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Be sure to have installed a recent version of [NodeJS](https://nodejs.org/)

Verify NodeJS installation with `node -v`

Set your bot token using configuration file, look at [config documentation](configuration.md).
Set your bot token using configuration file, look at [config documentation](https://sp3rick.github.io/GroupHelp/wiki/configuration/).

Open a terminal inside LibreGroupHelp folder and run this commands

Expand Down
16 changes: 10 additions & 6 deletions api/utils/antispam.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,16 @@ function linksValidator(string)
{
if(string.includes("://"))
string = string.split("://")[1];

var host = string.split("/")[0].toLowerCase();
if( !isValidHost(host) || !host.includes(".") )
return false;

if(string.includes("/"))

var host = "";
try {
host = new URL("https://"+string).hostname
if( !host.includes(".") )
return false;
} catch (error) {return false}

var afterHost = string.split(host).length > 1 ? string.split(host)[1] : false;
if( afterHost && (afterHost.startsWith("/") || afterHost.startsWith("#")) )
return string;

var doms = host.split(".");
Expand Down
26 changes: 25 additions & 1 deletion docs/documentation/GHBot.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ The down below lines are generated with [jsdoc2md](https://github.com/jsdoc2md/j
* [.db](#LGHInterface+db) : [<code>LGHDatabase</code>](#LGHDatabase)
* [.config](#LGHInterface+config) : <code>Object</code>
* [.onMessage(handler)](#LGHInterface+onMessage)
* [.onEditedMessage(handler)](#LGHInterface+onEditedMessage)
* [.onEditedMessageText(handler)](#LGHInterface+onEditedMessageText)
* [.onCallback(handler)](#LGHInterface+onCallback)
* [.sendMessage(userId, chatId, text, options)](#LGHInterface+sendMessage) ⇒ <code>Boolean</code> \| <code>Promise.&lt;TelegramBot.Message&gt;</code>
* [.sendPhoto(userId, chatId, photo, options, fileOptions)](#LGHInterface+sendPhoto) ⇒ <code>Boolean</code> \| <code>Promise.&lt;TelegramBot.Message&gt;</code>
Expand Down Expand Up @@ -208,10 +210,32 @@ LGHbot message event handler
| --- | --- | --- |
| handler | <code>function</code> | handler function |

<a name="LGHInterface+onEditedMessage"></a>

### lghInterface.onEditedMessage(handler)
LGHbot edited_message event handler

**Kind**: instance method of [<code>LGHInterface</code>](#LGHInterface)

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>function</code> | handler function |

<a name="LGHInterface+onEditedMessageText"></a>

### lghInterface.onEditedMessageText(handler)
LGHbot edited_message event handler

**Kind**: instance method of [<code>LGHInterface</code>](#LGHInterface)

| Param | Type | Description |
| --- | --- | --- |
| handler | <code>function</code> | handler function |

<a name="LGHInterface+onCallback"></a>

### lghInterface.onCallback(handler)
LGHbot callback event handler
LGHbot callback_query event handler

**Kind**: instance method of [<code>LGHInterface</code>](#LGHInterface)

Expand Down
7 changes: 5 additions & 2 deletions docs/documentation/TODO-List.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@ If you want an idea of what currently miss on the bot and you may want to implem
support all group help functions and more (+anti-sheduled messages[msg.is_from_offline], )
allow bot clone bot when user give a token
add optionally an userbot (when active implement in tagResolver.js)
user should have an option to delete also his warn or roles data from the entire database but accepting that he is going to be banned by any group where he got at least a warn and accepting that he is going to lose any acquired role on every group
make plugins more independed

-other things:

user should have an option to delete also his warn or roles data from the entire database but accepting that he is going to be banned by any group where he got at least a warn and accepting that he is going to lose any acquired role on every group
implement direct private settings with /*settings
add a setting on antiflood.js to count edited messages too
allow a plugin to add itself a button on settings page
implement direct private settings with /*settings
add a /commands command to help user to know bot commands, admin commands, and custom-group commands if avaiable
a check system to drop wrong formatted cb.data and waitingReply
allow to see perms calculation trough user perms, then roles by priority, then base group perms, going from left to right (or opposite)
Expand Down
4 changes: 3 additions & 1 deletion docs/documentation/events.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@ or
[chat](GHBot.md/#LGHChat),
[user](GHBot.md/#LGHUser)

GHBot currently has 2 events fully supported
GHBot currently has 4 events fully supported

```javascript
GHBot.onCallback( (cb, chat, user) => { console.log(cb) } )
GHBot.onMessage( (msg, chat, user) => { console.log(msg) } )
GHBot.onEditedMessage( (msg, chat, user) => { console.log(msg) } )
GHBot.onEditedMessageText( (msg, chat, user) => { console.log(msg) } )
```

---
Expand Down
3 changes: 2 additions & 1 deletion langs/en_en.json
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@
"FORWARD_PUNISHMENT" : "AntiSpam, user forwarded a message from an unallowed {type}",
"QUOTE_PUNISHMENT" : "AntiSpam, user quoted a message from an unallowed {type}",
"TGLINK_PUNISHMENT" : "AntiSpam, user sent an unallowed telegram link",
"TGLINK_BOT_PUNISHMENT" : "AntiSpam, user sent an unallowed bot username",
"LINK_PUNISHMENT" : "AntiSpam, user sent an unallowed link",
"CAPTCHA_PUNISHMENT" : "Captcha, user failed to solve the captcha",
"ANTISPAM_TGLINKS_DESCRIPTION" : "<b>📘 Telegram links</b>\nFrom this menu you can set a punishment for users who send messages containing Telegram links.\n\n<b>🎯 Username Antispam: </b> this option triggers the antispam when a <b>username</b> considered spam is sent.\n\n<b>Bots Antispam: </b>this option triggers the antispam when a Bot link is sent.\n\n<b>Punishment: </b>{punishment}\n<b>Deletion: </b>{deletion}",
Expand Down Expand Up @@ -283,7 +284,7 @@
"UNALLOWED_MEDIA_PUNISHMENT" : "Media, user sent {types} media",
"PAGE_LEFT_BUTTON" : "◀️ Page",
"PAGE_RIGHT_BUTTON" : "▶️ Page",
"WARNS_DESCRIPTION" : "<b>❗️ User warnings</b>\nThe warnings system allows you to give warnings to user for incorrect bahaivor in your group, before acutally punishing them.\n\nFrom this menu you can set:\n• The punishment to apply when warnings limit is hit\nthe maximum number of warns\n\n{punishmentText}\n<b>Max Warns allowed:</b> {limit}",
"WARNS_DESCRIPTION" : "<b>❗️ User warnings</b>\nThe warnings system allows you to give warnings to user for incorrect bahaivor in your group, before acutally punishing them.\n\nFrom this menu you can set:\n• The punishment to apply when warnings limit is hit\nThe maximum number of warns\n\n<b>Punishment: </b>{punishmentText}\n<b>Max Warns allowed:</b> {limit}",
"MAX_WARNS_ALLOWED" : "Max Warns allowed",
"SET_MAX_WARNS_BUTTON" : "🔢 Set maximum Warns allowed",
"WARNED_LIST_BUTTON" : "📜 Warned List",
Expand Down
102 changes: 73 additions & 29 deletions main.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
var LGHelpTemplate = require("./GHbot.js");
const LGHelpTemplate = require("./GHbot.js");
const {parseCommand} = require( __dirname + "/api/utils/utils.js" );
const EventEmitter = require("node:events");
const getDatabase = require( "./api/database.js" );
Expand All @@ -24,7 +24,7 @@ async function main(config) {
console.log("Starting a bot...")

var TGbot = new TelegramBot(config.botToken, {polling: true});
await TGbot.setWebHook("",{allowed_updates: JSON.stringify(["message", "edited_channel_post", "callback_query", "message_reaction", "message_reaction_count", "chat_member"])})
await TGbot.setWebHook("",{allowed_updates: JSON.stringify(["message", "edited_message", "edited_channel_post", "callback_query", "message_reaction", "message_reaction_count", "chat_member"])})
const bot = await TGbot.getMe();
TGbot.me = bot;

Expand All @@ -42,8 +42,21 @@ async function main(config) {
//some simplified variables
l = global.LGHLangs;


TGbot.on( "message", async (msg, metadata) => { try {
/**
* @typedef {Object} handleMessageReturn
* @param {LGHelpTemplate.LGHMessage} msg
* @param {LGHelpTemplate.LGHChat} chat
* @param {LGHelpTemplate.LGHUser} user
*/
/**
* @param {TelegramBot.Message} msg
* @param {TelegramBot.Metadata} metadata
* @description
* handles telegram raw messages and return various
* ready to use LibreGroupHelp objects
* @returns {handleMessageReturn}
*/
async function handleMessage(msg, metadata){ try {

if(!isChatAllowed(config, msg.chat.id)) return;

Expand Down Expand Up @@ -81,7 +94,9 @@ async function main(config) {

var creator = getOwner(adminList);
var newGroupText = l[chat.lang].NEW_GROUP;
newGroupText = (creator && !creator.is_anonymous) ? newGroupText.replace("{owner}",tag(".",creator.user.id)) : ".";
newGroupText = (creator && !creator.is_anonymous) ?
newGroupText.replace("{owner}",tag(".",creator.user.id)) :
newGroupText.replace("{owner}",".");

await GHbot.sendMessage(user.id, chat.id, newGroupText,{parse_mode:"HTML",
reply_markup :{inline_keyboard:[[{text: l[chat.lang].ADV_JOIN_CHANNEL, url: "https://t.me/LibreGroupHelp"}]]}
Expand All @@ -91,7 +106,7 @@ async function main(config) {
{text: l[chat.lang].LANGS_BUTTON2, callback_data: "LANGS_BUTTON:"+chat.id},
{text: l[chat.lang].SETTINGS_BUTTON, callback_data: "SETTINGS_SELECT:"+chat.id}]]}
})

}
chat = Object.assign( {}, ((chat.isGroup ? db.chats.get( chat.id ) : {})), chat );
msg.chat = chat;
Expand Down Expand Up @@ -154,36 +169,64 @@ async function main(config) {
}


try {
if(!user.lang)
{
console.log("somehow user.lang is not avaiable, logging message to futher debug");
console.log(msg);
return;
}
if(msg.waitingReply && msg.waitingReply.includes(":") && !chat.isGroup)
{
console.log("invalid message waitingReply group detected, logging message to futher debug");
console.log(msg);
return;
}
if(chat.id == user.id) chat.lang = user.lang;
GroupHelpBot.emit( "message", msg, chat, user );
GHCommand.messageEvent(msg, chat, user);
if ( chat.type == "private" ) GroupHelpBot.emit( "private", msg, chat, user );
} catch (err) {
console.log("Error after emitting a valid GroupHelpBot \"message\", i will log error then \"msg\", \"chat\", \"user\" ")
console.log(err);
//Final checks
if(!user.lang)
{
console.log("somehow user.lang is not avaiable, logging message to futher debug");
console.log(msg);
console.log(chat);
console.log(user);
return;
}
if(msg.waitingReply && msg.waitingReply.includes(":") && !chat.isGroup)
{
console.log("invalid message waitingReply group detected, logging message to futher debug");
console.log(msg);
return;
}
if(chat.id == user.id) chat.lang = user.lang;
return {msg, chat, user}
} catch (err) {
console.log("Error trying to handle GroupHelpBot Message, i will log error there \"msg\"");
console.log(err);
console.log(msg);
}}

TGbot.on( "message", async (msg, metadata) => { try {
var {msg, chat, user} = await handleMessage(msg, metadata);
GroupHelpBot.emit( "message", msg, chat, user );
GHCommand.messageEvent(msg, chat, user);
if ( chat.type == "private" ) GroupHelpBot.emit( "private", msg, chat, user );
} catch (err) {
console.log("Error in main.js on message event, i will log the error and then the received message");
console.log("Error after emitting an handled GroupHelpBot \"message\", i will log error then \"msg\", \"chat\", \"user\" ")
console.log(err);
console.log(msg);
console.log(chat);
console.log(user);
} } );

TGbot.on( "edited_message", async (msg) => { try {
var {msg, chat, user} = await handleMessage(msg);
GroupHelpBot.emit( "edited_message", msg, chat, user );
} catch (err) {
console.log("Error after emitting an handled GroupHelpBot \"edited_message\", i will log error then \"msg\", \"chat\", \"user\" ")
console.log(err);
console.log(msg);
console.log(chat);
console.log(user);
} } )

TGbot.on( "edited_message_text", async (msg) => { try {
var {msg, chat, user} = await handleMessage(msg);
GroupHelpBot.emit( "edited_message_text", msg, chat, user );
} catch (err) {
console.log("Error after emitting an handled GroupHelpBot \"edited_message_text\", i will log error then \"msg\", \"chat\", \"user\" ")
console.log(err);
console.log(msg);
console.log(chat);
console.log(user);
} } )



TGbot.on( "callback_query", async (cb) => { try {

if(!isChatAllowed(config, cb.message.chat.id)) return;
Expand Down Expand Up @@ -260,6 +303,7 @@ async function main(config) {
console.log(cb);
} } )

// handleMessage is not used here because im not sure is supported by the function
TGbot.on( "left_chat_member", (msg) => {

if(!isChatAllowed(config, msg.chat.id)) return;
Expand Down
Loading

0 comments on commit a823737

Please sign in to comment.