Skip to content

Commit

Permalink
🎉 Fixes and improvements
Browse files Browse the repository at this point in the history
- Improve: Delete useless file
- Improve: Add response to plain text
- Fix: Wrong initiate variable type of LBE
- Improve: Always reply to message ID; Delete process message finally
- Fix: Skip group / channel messages
  • Loading branch information
AnotiaWang committed Feb 17, 2022
1 parent 1c117e2 commit 38a8694
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 48 deletions.
11 changes: 0 additions & 11 deletions config.json

This file was deleted.

7 changes: 2 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { existsSync, readFileSync, writeFileSync } from 'fs';
import { handleMessage, handleCallbackQuery, launchBot, BOT_TOKEN, API_ID, API_HASH } from "./src/handler/index.js";
import {LogLevel} from "telegram/extensions/Logger.js";
import {CallbackQuery} from "telegram/events/CallbackQuery.js";
import {NewMessage} from "telegram/events/index.js";

const stringSession = new StringSession(existsSync('./data/.session') ? readFileSync('./data/.session', 'utf-8') : "");

Expand All @@ -18,13 +19,9 @@ writeFileSync('./data/.session', bot.session.save());
console.log('[Bot] Launched successfully.');

bot.setLogLevel(LogLevel.ERROR);
bot.addEventHandler(async (update) => {
if (update.className === 'UpdateNewMessage')
await handleMessage(update.message);
});
bot.addEventHandler(handleMessage, new NewMessage({}));
bot.addEventHandler(handleCallbackQuery, new CallbackQuery());


process.on('unhandledRejection', (reason, promise) => {
console.error(reason, 'Unhandled Rejection at', promise);
}).on('uncaughtException', error => {
Expand Down
2 changes: 1 addition & 1 deletion src/handler/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const template = {
downloading: 0,
total: 0,
service: DEFAULT_SERVICE,
lbe: DEFAULT_EXPR,
lbe: parseInt(DEFAULT_EXPR),
banned: false
};

Expand Down
16 changes: 12 additions & 4 deletions src/handler/message.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
import { handleCommand, initChatData, transfer } from "./index.js";
import {chatData, handleCommand, initChatData, transfer} from "./index.js";
import { bot } from "../../index.js";
import strings from "../strings.js";

export async function handleMessage(msg) {
export async function handleMessage(event) {
let msg = event.message;
if (msg.peerId.className !== 'PeerUser') return;
let chat = parseInt(msg.peerId.userId.value);
// console.log(msg);
initChatData(chat);
let lang = chatData[chat].lang;
if (isCommand(msg.message))
await handleCommand(msg);
else if (msg.media)
await transfer(msg)
await transfer(msg);
else
bot.sendMessage(chat, {
message: strings[lang].sendMeAFile
}).catch(() => null);
}

function isCommand(message) {
Expand Down
23 changes: 14 additions & 9 deletions src/handler/transfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function transfer(msg) {
fileSize = file.document.size;
if (file.document.mimeType === 'application/x-tgsticker') {
fileExt = 'tgs';
await bot.sendMessage(chat, {message: strings[lang].animatedStickers, parseMode: 'html', linkPreview: false});
await bot.sendMessage(chat, { message: strings[lang].animatedStickers, parseMode: 'html', linkPreview: false });
}
else
fileExt = mime.extension(file.document.mimeType);
Expand All @@ -33,7 +33,7 @@ export async function transfer(msg) {
fileExt = 'png';
}

if ((service === 'Catbox' && fileSize > 200000000) || (service === 'Litterbox' && fileSize > 1000000000))
if ((service === 'Catbox' && fileSize > 200000000) || (service === 'Litterbox' && fileSize > 1000000000))
return bot.sendMessage(chat, { message: strings[lang].err_FileTooBig.replace('{s}', service) });

editMsg = await bot.sendMessage(chat, { message: strings[lang].downloading, replyTo: msg.id });
Expand All @@ -48,7 +48,7 @@ export async function transfer(msg) {
console.log(`Downloading: ${filePath}`);
let buffer = await bot.downloadMedia(file, {});
fs.writeFileSync(filePath, buffer);
console.log(`File ${filePath} downloaded`);
console.log(`Downloaded ${filePath}, now uploading...`);
await bot.editMessage(chat, { message: editMsg.id, text: strings[lang].uploading.replace('{s}', service) });
let result = 'None';
try {
Expand All @@ -61,21 +61,26 @@ export async function transfer(msg) {
result = await LitterBox.upload(filePath, chatData[chat].lbe).catch((e) => {
throw new Error(e);
});
bot.editMessage(chat, {
message: editMsg.id, text: strings[lang].uploaded
.replace('{s}', service.toLowerCase() === 'catbox' ? '∞' : chatData[chat].lbe) + result
bot.sendMessage(chat, {
message: strings[lang].uploaded
.replace('{1}', service)
.replace('{2}', service.toLowerCase() === 'catbox' ? '∞' : (chatData[chat].lbe + ` ${strings[lang].hour}`))
.replace('{3}', result),
replyTo: msg.id
}).catch(() => null);
chatData[chat].total++;
console.log(`Uploaded ${filePath} to ${service}`);
}
catch (e) {
console.error(`Error when uploading file from ${chat}:`, e.message);
await bot.sendMessage(chat, { message: strings[lang].error + `\n${e.message}` });
console.error(`Upload ${filePath} failed:`, e.message);
await bot.sendMessage(chat, { message: strings[lang].error + `\n\n${e.message}`, replyTo: msg.id });
}
finally {
fs.rmSync(filePath);
chatData[chat].downloading--;
bot.deleteMessages(chat, [editMsg.id], { revoke: true }).catch(() => null);
if (LOG_CHANNEL_ID) {
let log = await bot.forwardMessages(LOG_CHANNEL_ID, {messages: msg.id, fromPeer: chat}).catch(console.error);
let log = await bot.forwardMessages(LOG_CHANNEL_ID, { messages: msg.id, fromPeer: chat }).catch(console.error);
await bot.sendMessage(LOG_CHANNEL_ID, { message: `From: \`${chat}\`\nService: ${service}\nResult: \`${result}\``, replyTo: log[0].id });
}
}
Expand Down
15 changes: 7 additions & 8 deletions src/i18n/en_US.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "English",
"help": "🐱 <b>Welcome to Catbox Uploader!</b>\n\nThis bot can upload your files to <a href=\"https://catbox.moe\">Catbox</a> or <a href=\"https://litterbox.catbox.moe\">Litterbox</a>, and return the file's share link. \nThe files you uploaded mustn't violate the <a href=\"https://catbox.moe/faq.php\">Catbox ToS</a> and Litterbox ToS.\n\nCommands:\n/help - Send this help info\n/settings - Choose a language, service or file expiration.\n/upload - (in groups) Reply to a message with file to upload.\n\nTake a look at my channel @atashare and @atabots for interesting websites and update notes!\nSource Code:<a href=\"https://github.com/AnotiaWang/TG_Catbox_Uploader\">GitHub</a>",
"help": "🐱 <b>Welcome to Catbox Uploader!</b>\n\nThis bot can upload your files to <a href=\"https://catbox.moe\">Catbox</a> or <a href=\"https://litterbox.catbox.moe\">Litterbox</a>, and return the file's share link. \nThe files you uploaded mustn't violate the <a href=\"https://catbox.moe/faq.php\">Catbox ToS</a> and Litterbox ToS.\n\nCommands:\n/help - Send this help info\n/settings - Choose a language, service or file expiration.\n\nTake a look at my channel @atashare and @atabots for interesting websites and update notes!\nSource code:<a href=\"https://github.com/AnotiaWang/TG_Catbox_Uploader\">GitHub</a>",
"downloading": "Downloading...",
"uploading": "File downloaded successfully. Now uploading to {s}...",
"uploaded": "Uploaded! Link (available in {s}) 👇\n",
"error": "Upload failed!",
"flood_protection": "Please wait for the current files to finish uploading. Max files allowed at one time {s}.",
"uploaded": "🗃️ Uploaded Successfully!\n\nService: {1}\nValidity: {2}\nLink: {3}",
"error": "😥 Upload failed!",
"flood_protection": "🚫 Please wait for the current files to finish uploading. Max files allowed at one time {s}.",
"setSuccess": "√ Set!",
"langSetText": "√ Language set to English. Send /help to see what I can do! ",
"err_FileTooBig": "File too big,exceeds {s} limit!\n\nCatbox limit: Max 200 MB per file\nLitterbox limit: Max 1 GB per file",
"err_FileTooBig": "🚫 File too big,exceeds {s} limit!\n\nCatbox limit: Max 200 MB per file\nLitterbox limit: Max 1 GB per file",
"reloadSuccess": "✅ Reloaded strings.json & config.json",
"settings": "<b>⚙ Settings</b>",
"help_settings": "\n\nTap the buttons below to see description and corresponding options.",
Expand All @@ -18,8 +18,6 @@
"help_setService": "\n\n<a href='https://catbox.moe'>Catbox</a>: No expiration, limited to 200 MB per file\n<a href='https://litterbox.catbox.moe'>Litterbox</a>: Expired after 1/12/24/72 hours, limited to 1 GB per file\n\nNote: You can only upload to one service at a time.",
"settings_setExpr": "⏰ Litterbox file expiration",
"settings_back": "🔙 Back",
"settings_setLitterBoxExprSuccess": "Litterbox file expiration set to {s}.",
"settings_setServiceSuccess": "√ Storage service set to {s}",
"saveDataSuccess": "Data saved.",
"hour": " hour(s)",
"serviceError": "Service error: {s}",
Expand All @@ -29,5 +27,6 @@
"error_banned": "You are banned from using this bot.",
"banned": "User is now banned from using this bot.",
"unbanned": "User is now unbanned.",
"userNotFound": "User not found."
"userNotFound": "User not found.",
"sendMeAFile": "👋 Send me a file to upload. Send /help to see what I can do!"
}
19 changes: 9 additions & 10 deletions src/i18n/zh_CN.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
{
"name": "简体中文",
"help": "🐱 <b>欢迎使用 Catbox Uploader!</b>\n\n本机器人可以将您发送的文件上传到 <a href=\"https://catbox.moe\">Catbox</a> 或 <a href=\"https://litterbox.catbox.moe\">Litterbox</a>,并返回文件的分享链接。\n上传的文件不得违反 <a href=\"https://catbox.moe/faq.php\">Catbox ToS</a> 以及 Litterbox ToS。\n\n命令列表:\n/help - 显示帮助信息\n/settings - 设置语言、存储服务、文件有效时长\n/upload -(群组中)回复一条带文件的消息以上传\n\n网络资源分享频道: @atashare\nBot 更新频道:@atabots\nBot 源码:<a href=\"https://github.com/AnotiaWang/TG_Catbox_Uploader\">GitHub</a>",
"downloading": "正在下载...",
"uploading": "文件下载完成,正在上传到 {s}...",
"uploaded": "上传完成!文件链接(有效时长 {s})👇\n",
"error": "上传失败!",
"flood_protection": "请先等待当前所有任务完成。最多同时下载 {s} 个文件。",
"help": "🐱 <b>欢迎使用 Catbox Uploader!</b>\n\n本机器人可以将您发送的文件上传到 <a href=\"https://catbox.moe\">Catbox</a> 或 <a href=\"https://litterbox.catbox.moe\">Litterbox</a>,并返回文件的分享链接。\n上传的文件不得违反 <a href=\"https://catbox.moe/faq.php\">Catbox ToS</a> 以及 Litterbox ToS。\n\n命令列表:\n/help - 显示帮助信息\n/settings - 设置语言、存储服务、文件有效时长\n\n网络资源分享频道: @atashare\nBot 更新频道:@atabots\nBot 源码:<a href=\"https://github.com/AnotiaWang/TG_Catbox_Uploader\">GitHub</a>",
"downloading": "正在下载文件...",
"uploading": "正在上传至 {s}...",
"uploaded": "🗃️ 上传完成!\n\n存储服务:{1}\n有效期:{2}\n链接:{3}",
"error": "😥 上传失败!",
"flood_protection": "🚫 请先等待当前所有任务完成。最多同时下载 {s} 个文件。",
"setSuccess": "√ 设置成功",
"langSetText": "√ 已设置为简体中文。发送 /help 看看我能做什么!",
"err_FileTooBig": "文件过大,超出 {s} 限制!\n\nCatbox 限制:单文件最大 200 MB\nLitterbox 限制:单文件最大 1 GB",
"err_FileTooBig": "🚫 文件过大,超出 {s} 限制!\n\nCatbox 限制:单文件最大 200 MB\nLitterbox 限制:单文件最大 1 GB",
"reloadSuccess": "✅ 已重新加载 config.json 和 strings.json",
"settings": "⚙ 设置",
"help_settings": "\n\n单击下方的按钮查看相关描述及选项。",
Expand All @@ -17,8 +17,6 @@
"settings_setService": "☁ 存储服务",
"help_setService": "\n\n<a href='https://catbox.moe'>Catbox</a> 文件不限时长,单文件限制 200 MB。\n<a href='https://litterbox.catbox.moe'>Litterbox</a> 文件有时限(1/12/24/72 小时),单文件限制 1 GB。\n\n一次只能选择将文件上传到其中一个服务。",
"settings_setExpr": "⏰ Litterbox 文件有效期",
"settings_setLitterBoxExprSuccess": "Litterbox 的文件有效时长已设置为 {s}。",
"settings_setServiceSuccess": "√ 存储服务已设置为 {s}",
"settings_back": "🔙 返回",
"saveDataSuccess": "成功保存数据。",
"hour": " 小时",
Expand All @@ -29,5 +27,6 @@
"error_banned": "您已经被禁止使用此机器人。",
"banned": "已封禁此用户。",
"unbanned": "已解封此用户。",
"userNotFound": "未找到此用户。"
"userNotFound": "未找到此用户。",
"sendMeAFile": "👋 发送一个文件,以将其上传到 Catbox 或 Litterbox。您可以发送 /help 命令查看详情。"
}

0 comments on commit 38a8694

Please sign in to comment.