├── .eslintrc.json ├── .gitignore ├── Dockerfile ├── README.md ├── docker-compose.dev.yml ├── docker-compose.yml ├── hataMesaji.txt ├── help.md ├── helpAdmin.md ├── logs └── .gitkeep ├── package-lock.json ├── package.json ├── pm2.json ├── sample.env ├── scripts └── deploy.sh ├── sourcess_controller.js ├── src ├── commands │ ├── announcement.js │ ├── ban.js │ ├── discord.js │ ├── github.js │ ├── group.js │ ├── hastebinize.js │ ├── help.js │ ├── index.js │ ├── kaynak.js │ ├── kontrol.js │ ├── pin.js │ ├── report.js │ ├── twitter.js │ ├── unban.js │ └── youtube.js ├── handlers │ ├── callbackHandler.js │ ├── easterEggHandler.js │ ├── index.js │ ├── joinedLeftUserHandler.js │ └── textHandler.js ├── index.js └── utils │ ├── apiAuth.js │ ├── errorMessage.js │ ├── forAdmins.js │ ├── hastebinize.js │ ├── index.js │ └── log.js ├── telegram.js └── telegram_func.js /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "commonjs": true, 4 | "es6": true, 5 | "node": true 6 | }, 7 | "extends": [ 8 | "standard" 9 | ], 10 | "globals": { 11 | "Atomics": "readonly", 12 | "SharedArrayBuffer": "readonly" 13 | }, 14 | "parserOptions": { 15 | "ecmaVersion": 2020 16 | }, 17 | "rules": { 18 | "no-new": "off", 19 | "no-multi-spaces": "off" 20 | } 21 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs/log_* 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .idea 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # Optional npm cache directory 48 | .npm 49 | 50 | # Optional eslint cache 51 | .eslintcache 52 | 53 | # Optional REPL history 54 | .node_repl_history 55 | 56 | # Output of 'npm pack' 57 | *.tgz 58 | 59 | # Yarn Integrity file 60 | .yarn-integrity 61 | 62 | # dotenv environment variables file 63 | .env 64 | .env.test 65 | 66 | # parcel-bundler cache (https://parceljs.org/) 67 | .cache 68 | 69 | # next.js build output 70 | .next 71 | 72 | # nuxt.js build output 73 | .nuxt 74 | 75 | # vuepress build output 76 | .vuepress/dist 77 | 78 | # Serverless directories 79 | .serverless/ 80 | 81 | # FuseBox cache 82 | .fusebox/ 83 | 84 | # DynamoDB Local files 85 | .dynamodb/ 86 | 87 | # pinignore file 88 | .pinignore -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM node:14 2 | 3 | RUN mkdir /var/bot/ 4 | 5 | WORKDIR /var/bot/ 6 | 7 | COPY . /var/bot/ 8 | 9 | RUN npm install 10 | 11 | RUN npm install pm2 -g 12 | 13 | CMD [ "pm2-runtime", "start", "pm2.json" ] 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # eksiCode Telegram Botu 2 | 3 | ## Nedir 4 | 5 | Bu script, http://eksicode.org telegram grupları üzerindeki kayıtlı üye sayılarını ölçmek 6 | ve chat geliştirmeleri için yazılmaktadır. 7 | 8 | ### Nasıl Çalıştırılır 9 | 10 | - UYARI: Docker çalışırken git branch'ını değiştirmeyin. 11 | 12 | - Paketleri yükleyin: `npm i` 13 | 14 | - sample.env dosyasındaki örnek ayarlara göre bir .env dosyası oluşturun. 15 | 16 | - Proje kök dizninde `.pinignore` adında dosya oluşturun. 17 | 18 | - Docker'ı çalıştırın: `docker-compose up --build` 19 | 20 | ## Bot Komutları 21 | 22 | ### Genel 23 | 24 | - `/help` - Komutları listeler. 25 | 26 | - `/yardim` - Komutları listeler. 27 | 28 | - `!kaynak `: Kaynak URL'sini Ekşicode veritabanına ekler. 29 | 30 | - `!kanal ` - kanalları listeler. 31 | 32 | - `!discord` - Discord sunucumuz. 33 | 34 | - `!duyuru` - Duyuru kanalımız. 35 | 36 | - `!hastebinize` - Kod içerikli / Uzun mesajları bu komut ile cevaplayarak hastebin'e yükleyebilirsiniz. 37 | 38 | 39 | ### Yönetim Komutları 40 | 41 | #### `/ban ` / `/unban` 42 | Bir kullanıcıyı banlamak için herhangi bir gruptayken kullanıcının mesajını `/ban` komutuyla cevaplamanız gerekmektedir. Ban komutuyla birlikte sebebini de yazabilirsiniz. Eğer bir kullanıcının banını kaldırmak istiyorsanız Admin kanalına gönderilen bildirim mesajını `/unban` komutu ile cevaplayın. 43 | 44 | #### `/pin ` 45 | `mesaj` argümanını tüm Ekşicode gruplarına gönderir ve sabitler. 46 | 47 | 48 | #### `/kontrol ` 49 | 50 | Boş kullanıldığında onaylanmamış kaynakları listeler. Kaynakları onaylamak için komuta argüman olarak onaylamak istediğiniz kaynakların numaralarını boşlukla ayırarak yazınız. Onaylanmamış bir kaynağı silmek için silmek istediğiniz kaynağın numarasının başına `!` işareti koyun. 51 | 52 | ## Hata Mesajları 53 | 54 | Siz de bu repoyu forklayıp `hataMesaji.txt` dosyası içerisine hata mesajı için ünlem ekleyebilirsiniz. 55 | 56 | ## .pinignore dosyası 57 | 58 | `/pin` komutunun çalışmamasını istediğiniz kanalın ID'lerini .pinignore dosyasına ekleyerek istisnalar oluşturabilirsiniz. 59 | -------------------------------------------------------------------------------- /docker-compose.dev.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | bot: 4 | container_name: eksicodeBot 5 | build: ./ 6 | volumes: 7 | - ./:/var/bot 8 | env_file: 9 | - .env 10 | network_mode: "host" 11 | 12 | volumes: 13 | bot: 14 | 15 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | bot: 4 | container_name: eksicodeBot 5 | build: ./ 6 | volumes: 7 | - ./:/var/bot 8 | env_file: 9 | - .env 10 | networks: 11 | - eksicode_nw 12 | 13 | volumes: 14 | bot: 15 | 16 | networks: 17 | eksicode_nw: 18 | -------------------------------------------------------------------------------- /hataMesaji.txt: -------------------------------------------------------------------------------- 1 | Ah be! 2 | Allah kahretsin! 3 | Eyvahlar olsun! 4 | Fuck! 5 | Kurwa! 6 | Lanet olsun! 7 | Tüh be! 8 | Wow! 9 | Birbirilerine püskevit ikram ediyorlar! Ama 10 | Scheiße! 11 | Hooooooaydoooaa! 12 | Olmadı, alamadı, olamayordu! 13 | Bir ihtimal daha var; o da 14 | Gözlerin doğuyor gecelerime ve 15 | Lanet olsun adamım! 16 | Oops! -------------------------------------------------------------------------------- /help.md: -------------------------------------------------------------------------------- 1 | • `/help | /yardim` - Bot komutlarını listeler. 2 | 3 | • `!kaynak ` - Kaynak URL'sini Ekşicode veritabanına ekler. 4 | 5 | • `!grup ` - Ekşicode grupları arasında arama yapar. 6 | 7 | • `!discord` - Discord sunucumuza katılın. 8 | 9 | • `!duyuru` - Duyuru kanalımıza katılın. 10 | 11 | • `!youtube` - Youtube kanalımıza abone olun. 12 | 13 | • `!github` - Github hesabımıza göz atın. 14 | 15 | • `!twitter` - Twitter hesabımızı takip edin. 16 | 17 | • `!report` - Grup yöneticilerini etiketler 18 | 19 | • `!hastebinize` - Kod içerikli / Uzun mesajları bu komut ile cevaplayarak hastebin'e yükleyebilirsiniz. -------------------------------------------------------------------------------- /helpAdmin.md: -------------------------------------------------------------------------------- 1 | • `/help | /yardim` - Bot komutlarını listeler. 2 | 3 | • `!kaynak ` - Kaynak URL'sini Ekşicode veritabanına ekler. 4 | 5 | • `!grup ` - Ekşicode grupları arasında arama yapar. 6 | 7 | • `!discord` - Discord sunucumuza katılın. 8 | 9 | • `!duyuru` - Duyuru kanalımıza katılın. 10 | 11 | • `!youtube` - Youtube kanalımıza abone olun. 12 | 13 | • `!github` - Github hesabımıza göz atın. 14 | 15 | • `!twitter` - Twitter hesabımızı takip edin. 16 | 17 | • `!report` - Grup yöneticilerini etiketler. 18 | 19 | • `!hastebinize` - Kod içerikli / Uzun mesajları bu komut ile cevaplayarak hastebin'e yükleyebilirsiniz. 20 | 21 | 22 | *Yönetim Komutları* 23 | 24 | • `/ban | /unban` 25 | 26 | Bir kullanıcıyı banlamak için herhangi bir gruptayken kullanıcının mesajını `/ban` komutuyla cevaplamanız gerekmektedir. Ban komutuyla birlikte sebebini de yazabilirsiniz. Eğer bir kullanıcının banını kaldırmak istiyorsanız Admin kanalına gönderilen bildirim mesajını `/unban` komutu ile cevaplayın. 27 | 28 | • `/pin ` 29 | 30 | `mesaj` argümanını tüm Ekşicode gruplarına gönderir ve sabitler. 31 | 32 | • `/kontrol ` 33 | 34 | Boş kullanıldığında onaylanmamış kaynakları listeler. Kaynakları onaylamak için komuta argüman olarak onaylamak istediğiniz kaynakların numaralarını boşlukla ayırarak yazınız. Onaylanmamış bir kaynağı silmek için silmek istediğiniz kaynağın numarasının başına `!` işareti koyun. -------------------------------------------------------------------------------- /logs/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Eksicode/eksicode-telegrambot/fbc3e01c8bfb12705a698dc2fdcc9105bcbe7cdb/logs/.gitkeep -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eksicodebot", 3 | "version": "2.0.0", 4 | "description": "eksicode.org telegram bot", 5 | "main": "telegram.js", 6 | "scripts": { 7 | "start": "node telegram.js" 8 | }, 9 | "keywords": [ 10 | "eksicode", 11 | "eksi", 12 | "telegram", 13 | "bot" 14 | ], 15 | "author": "Davut KARA & Mkltkn & Atakan Ermiş", 16 | "license": "MIT", 17 | "dependencies": { 18 | "axios": "^0.21.2", 19 | "dotenv": "^6.0.0", 20 | "http": "0.0.1-security", 21 | "node-cron": "^3.0.1", 22 | "node-html-parser": "^1.1.16", 23 | "path": "^0.12.7", 24 | "request": "^2.88.2", 25 | "telegraf": "^4.0.2" 26 | }, 27 | "devDependencies": { 28 | "eslint": "^6.7.2", 29 | "eslint-config-standard": "^14.1.0", 30 | "eslint-plugin-import": "^2.19.1", 31 | "eslint-plugin-node": "^10.0.0", 32 | "eslint-plugin-promise": "^4.2.1", 33 | "eslint-plugin-standard": "^4.0.1" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /pm2.json: -------------------------------------------------------------------------------- 1 | { 2 | "apps": [ 3 | { 4 | "name": "eksicodeBot-user", 5 | "script": "telegram.js", 6 | "listen_timeout": 5000, 7 | "watch": false, 8 | "instances": 1, 9 | "wait_ready": true, 10 | "restart_delay": 5000 11 | }, 12 | { 13 | "name": "eksicodeBot-func", 14 | "script": "telegram_func.js", 15 | "ignore_watch": [ 16 | "logs", 17 | "node_modules" 18 | ], 19 | "watch": true, 20 | "instances": 1 21 | },{ 22 | "name": "sourcess_controller", 23 | "script": "sourcess_controller.js", 24 | "listen_timeout": 5000, 25 | "watch": false, 26 | "instances": 1, 27 | "wait_ready": true, 28 | "restart_delay": 5000 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /sample.env: -------------------------------------------------------------------------------- 1 | BOT_TOKEN= 2 | API_URL= 3 | API_USER= 4 | API_PASS= 5 | ADMIN_CH_ID= -------------------------------------------------------------------------------- /scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | cd /home/eksicode-telegrambot 2 | docker stop eksicodeBot 3 | git pull origin master 4 | npm ci 5 | docker-compose up --build -d -------------------------------------------------------------------------------- /sourcess_controller.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | require('dotenv').config({ 3 | path: path.join(__dirname, '.env') 4 | }) 5 | const axios = require('axios') 6 | const { apiAuth } = require('./src/utils') 7 | const cron = require('node-cron') 8 | 9 | /** 10 | * Cron Job 11 | * 12 | * Run crone job everyday 13 | * 14 | * @param '00 01 * * *' Evertyday will backup at 01 15 | */ 16 | 17 | cron.schedule('00 01 * * *', async () => { 18 | // cron.schedule('1 * * * * *', async () => { 19 | console.log('Eksicode Source Checking Process Started') 20 | console.log('-----------------------------------------') 21 | 22 | let allSourcess 23 | const jwt = await apiAuth() 24 | 25 | const changeApprove = async (id, status) => { 26 | try { 27 | const requestData = { 28 | approved: status 29 | } 30 | const config = { 31 | headers: { 32 | 'Content-Type': 'application/json', 33 | Authorization: 'Bearer ' + jwt 34 | } 35 | } 36 | axios.put('https://api.eksicode.org/kaynaklars/' + id, requestData, config) 37 | } catch (err) { 38 | console.error(err) 39 | } 40 | } 41 | 42 | axios.get('https://api.eksicode.org/kaynaklars?_limit=10000000&_sort=id:ASC') 43 | .then(async (response) => { 44 | allSourcess = response.data 45 | }) 46 | .then(() => { 47 | const getConfig = { 48 | timeout: 60000, 49 | maxContentLength: 500 * 1000 * 1000, 50 | headers: { 51 | 'Content-Type': 'text/html; charset=UTF-8', 52 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9', 53 | Authorization: 'Bearer ' + jwt 54 | } 55 | } 56 | console.log('total links: ' + allSourcess.length) 57 | let number = 0 58 | allSourcess.forEach( 59 | async (source) => { 60 | axios.get(source.doc_link, getConfig) 61 | .then(async (response) => { 62 | if (response.status === '' || response.status >= 399) { 63 | // console.log(response.status) 64 | await changeApprove(source.id, 'false') 65 | number++ 66 | throw new Error(number + ' ' + source.doc_link + ' is down' + ' - ') 67 | } else if (response.status <= 399 && source.status === 'false') { 68 | await changeApprove(source.id, 'true') 69 | number++ 70 | } else { 71 | console.log(number + '/' + allSourcess.length + ' - ' + response.status + ' ' + source.doc_link + ' is up') 72 | number++ 73 | } 74 | }) 75 | .catch((error) => { 76 | console.log(error) 77 | }) 78 | }) 79 | 80 | if (allSourcess.length === number) { 81 | console.log('Eksicode Source Checking Process finished') 82 | console.log('-----------------------------------------') 83 | } 84 | }) 85 | .catch((error) => { 86 | console.log(error) 87 | }) 88 | }) 89 | -------------------------------------------------------------------------------- /src/commands/announcement.js: -------------------------------------------------------------------------------- 1 | async function announcementCommand (ctx) { 2 | ctx.reply('Duyuru Kanalımıza Girin.', { 3 | reply_markup: { 4 | inline_keyboard: [ 5 | [ 6 | { 7 | text: '📣 Duyuru Kanalı', 8 | url: 'https://t.me/joinchat/AAAAAE9tV17jUdYexFPQXg' 9 | } 10 | ] 11 | ] 12 | } 13 | }) 14 | } 15 | 16 | module.exports = announcementCommand 17 | -------------------------------------------------------------------------------- /src/commands/ban.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | const { log } = require('../utils') 3 | 4 | function generateBanMessage (ctx, args) { 5 | const userName = ctx.message.reply_to_message.from.username 6 | const firstName = ctx.message.reply_to_message.from.first_name 7 | const lastName = ctx.message.reply_to_message.from.last_name 8 | const userId = ctx.message.reply_to_message.from.id 9 | 10 | const banned = `[${firstName || lastName || userName}](tg://user?id=${userId})` 11 | const admin = `[${ctx.from.first_name || ctx.from.last_name || ctx.from.username}](tg://user?id=${ctx.from.id})` 12 | 13 | return `*${userId}* *BAN* 🔨 🛫 \n\n*Banlanan Kişi*: ${banned}\n*Banlayan Admin*: ${admin}\n*Sebep*: ${args || 'Belirtilmemiş'}` 14 | } 15 | 16 | async function banCommand (ctx) { 17 | try { 18 | await ctx.deleteMessage() 19 | 20 | const args = ctx.message.text.slice(ctx.message.entities[0].length + 1) 21 | 22 | const toBeBanned = await ctx.telegram.getChatMember( 23 | process.env.ADMIN_CH_ID, 24 | ctx.message.reply_to_message.from.id 25 | ) 26 | 27 | const isToBeBannedNotAdmin = !toBeBanned || (toBeBanned.status === 'kicked' || toBeBanned.status === 'left') 28 | 29 | if (isToBeBannedNotAdmin && ctx.message.reply_to_message) { 30 | const userId = ctx.message.reply_to_message.from.id 31 | 32 | const request = await axios.get(`${process.env.API_URL}/telegrams`) 33 | const groups = request.data 34 | 35 | groups.map(async e => { 36 | await ctx.telegram.kickChatMember(e.channelID, userId) 37 | }) 38 | 39 | await ctx.telegram.sendMessage(process.env.ADMIN_CH_ID, 40 | generateBanMessage(ctx, args), 41 | { 42 | parse_mode: 'Markdown', 43 | reply_markup: { 44 | inline_keyboard: [ 45 | [ 46 | { 47 | text: 'Geri Al', 48 | callback_data: `unban: ${userId}` 49 | } 50 | ] 51 | ] 52 | } 53 | }) 54 | await log(ctx, 'ban') 55 | } else { 56 | console.log('Ban Error: Yetkisiz İşlem / Hatalı Kullanım') 57 | } 58 | } catch (err) { 59 | console.log('Ban Error: Hata aşağıdadır.') 60 | console.error(err) 61 | } 62 | } 63 | 64 | module.exports = banCommand 65 | -------------------------------------------------------------------------------- /src/commands/discord.js: -------------------------------------------------------------------------------- 1 | function discordCommand (ctx) { 2 | ctx.reply('Discord Sunucumuza Girin.', { 3 | reply_markup: { 4 | inline_keyboard: [ 5 | [ 6 | { 7 | text: '🎙 Discord Sunucumuz', 8 | url: 'https://discord.gg/cZRhbuJ' 9 | } 10 | ] 11 | ] 12 | } 13 | }) 14 | } 15 | 16 | module.exports = discordCommand 17 | -------------------------------------------------------------------------------- /src/commands/github.js: -------------------------------------------------------------------------------- 1 | function githubCommand (ctx) { 2 | ctx.reply('Github hesabımıza göz atın.', { 3 | reply_markup: { 4 | inline_keyboard: [ 5 | [ 6 | { 7 | text: '👨‍💻 Github', 8 | url: 'https://github.com/Eksicode' 9 | } 10 | ] 11 | ] 12 | } 13 | }) 14 | } 15 | 16 | module.exports = githubCommand 17 | -------------------------------------------------------------------------------- /src/commands/group.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | const { errorMessage } = require('../utils') 3 | 4 | class GroupBot { 5 | constructor (ctx) { 6 | this.args = ctx.message.text.slice(ctx.message.text.split(' ')[0].length + 1) 7 | this.query = ['tümü', '*'].includes(this.args) ? '' : this.args 8 | this.groups = [] 9 | this.answer = '' 10 | 11 | this.executeCommand(ctx) 12 | } 13 | 14 | async executeCommand (ctx) { 15 | try { 16 | if (!this.args) { 17 | ctx.reply('Kullanım: !grup ') 18 | return 1 19 | } 20 | await this.fetchGroups() 21 | this.formatAnswer() 22 | this.send(ctx) 23 | } catch (err) { 24 | console.error(err) 25 | ctx.reply(`${errorMessage()} Bir hata oluştu. Lütfen daha sonra tekrar deneyin.`) 26 | } 27 | } 28 | 29 | async fetchGroups () { 30 | const groupsRequest = await axios.get(`${process.env.API_URL}/telegrams`, { 31 | params: { 32 | _sort: 'name:ASC', 33 | name_contains: this.query, 34 | } 35 | }) 36 | this.groups = await groupsRequest.data 37 | } 38 | 39 | formatAnswer () { 40 | if (this.groups.length) { 41 | this.answer = `*Sonuçlar:*\n\n ${this.groups.map(e => `- [${e.name}](${e.link})`).join('\n')}` 42 | } else { 43 | this.answer = `${errorMessage()} Sonuç bulunamadı. 😕` 44 | } 45 | } 46 | 47 | send (ctx) { 48 | ctx.replyWithMarkdown(this.answer) 49 | } 50 | } 51 | 52 | module.exports = GroupBot 53 | -------------------------------------------------------------------------------- /src/commands/hastebinize.js: -------------------------------------------------------------------------------- 1 | const { hastebinize, errorMessage } = require('../utils') 2 | 3 | async function hastebinizeCommand (ctx) { 4 | try { 5 | const replyToMessage = ctx.message.reply_to_message // Message Context to be hastebinized. 6 | 7 | const userName = replyToMessage.from.username || // Username (first name or last name if username is not available) 8 | replyToMessage.from.first_name || // of the sender of the message to be hastebinized. 9 | replyToMessage.from.last_name 10 | 11 | const hastebinized = await hastebinize(replyToMessage.text) 12 | 13 | await ctx.replyWithMarkdown(`[${userName}](tg://user?id=${replyToMessage.from.id}): ` + hastebinized, { // sends hastebinized message to chat. 14 | reply_to_message_id: ctx.message.message_id 15 | }) 16 | 17 | await ctx.telegram.deleteMessage(ctx.message.chat.id, replyToMessage.message_id) // Removes hastebinized message 18 | await ctx.telegram.deleteMessage(ctx.message.chat.id, ctx.message.message_id) // Removes command message 19 | } catch (err) { 20 | console.error(err) 21 | return ctx.reply(`${errorMessage()} Bir hata oluştu. Lütfen daha sonra tekrar deneyin.`) 22 | } 23 | } 24 | 25 | module.exports = hastebinizeCommand 26 | -------------------------------------------------------------------------------- /src/commands/help.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | 3 | const helpText = fs.readFileSync('help.md', 'utf-8') 4 | 5 | const helpTextAdmin = fs.readFileSync('helpAdmin.md', 'utf-8') 6 | 7 | function helpCommand (ctx) { 8 | if (ctx.message.chat.id.toString() === process.env.ADMIN_CH_ID) { 9 | ctx.replyWithMarkdown(helpTextAdmin) 10 | } else { 11 | ctx.replyWithMarkdown(helpText) 12 | } 13 | } 14 | 15 | module.exports = helpCommand 16 | -------------------------------------------------------------------------------- /src/commands/index.js: -------------------------------------------------------------------------------- 1 | const SourceBot = require('./kaynak') 2 | const GroupBot = require('./group') 3 | const banCommand = require('./ban') 4 | const unbanCommand = require('./unban') 5 | const helpCommand = require('./help') 6 | const discordCommand = require('./discord') 7 | const youtubeCommand = require('./youtube') 8 | const githubCommand = require('./github') 9 | const twitterCommand = require('./twitter') 10 | const announcementCommand = require('./announcement') 11 | const pinCommand = require('./pin') 12 | const reportCommand = require('./report') 13 | const kontrolCommand = require('./kontrol') 14 | const hastebinizeCommand = require('./hastebinize') 15 | 16 | module.exports = { 17 | SourceBot, 18 | GroupBot, 19 | banCommand, 20 | helpCommand, 21 | discordCommand, 22 | unbanCommand, 23 | announcementCommand, 24 | pinCommand, 25 | youtubeCommand, 26 | githubCommand, 27 | twitterCommand, 28 | reportCommand, 29 | kontrolCommand, 30 | hastebinizeCommand 31 | } 32 | -------------------------------------------------------------------------------- /src/commands/kaynak.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | const { parse } = require('node-html-parser') 3 | const { apiAuth, errorMessage } = require('../utils') 4 | 5 | class Source { 6 | constructor (url, tgChannel, tgUser, title, headers) { 7 | this.url = url 8 | this.title = title 9 | this.headers = headers 10 | this.tgChannel = tgChannel 11 | this.tgChannel = tgUser 12 | } 13 | } 14 | 15 | class SourceBot { 16 | constructor (ctx) { 17 | this.tgChannel = ctx.message.chat.id 18 | this.tgUser = ctx.message.from.id 19 | this.messageId = ctx.message.message_id 20 | this.entities = ctx.message.entities 21 | this.text = ctx.message.text 22 | this.sources = [] 23 | 24 | this.executeCommand(ctx) 25 | } 26 | 27 | async executeCommand (ctx) { 28 | let message 29 | try { 30 | this.createSourcesFromLinks() 31 | 32 | if (!this.sources.length) { 33 | ctx.reply('Kullanım: !kaynak ') 34 | return 1 35 | } 36 | 37 | message = await ctx.reply('Kaynak ekleniyor...', { reply_to_message_id: this.messageId }) 38 | 39 | await this.addHeadersToSources() 40 | await this.addTitlesToSources() 41 | await this.postToAPI() 42 | 43 | ctx.telegram.editMessageText(message.chat.id, message.message_id, undefined, 'Teşekkürler! Kaynaklar başarıyla eklendi.') 44 | } catch (err) { 45 | console.error(err) 46 | ctx.telegram.editMessageText(message.chat.id, message.message_id, undefined, `${errorMessage()} Bir hata oluştu. Lütfen daha sonra tekrar deneyin.`) 47 | } 48 | } 49 | 50 | createSourcesFromLinks () { 51 | try { 52 | this.entities.map(e => { 53 | if (e.type === 'url') { 54 | const link = this.text.slice(e.offset, e.offset + e.length) 55 | const linkHttpAdded = link.startsWith('http://') || link.startsWith('https://') ? link : 'http://' + link 56 | this.sources.push(new Source(linkHttpAdded, this.tgChannel, this.tgUser)) 57 | } 58 | }) 59 | } catch (err) { 60 | this.sources = [] 61 | } 62 | } 63 | 64 | async addHeadersToSources () { 65 | await Promise.all(this.sources.map(async e => { 66 | const headRequest = await axios.head(e.url) 67 | e.headers = headRequest.headers 68 | })) 69 | } 70 | 71 | async addTitlesToSources () { 72 | await Promise.all(this.sources.map(async e => { 73 | if (e?.headers['content-type']?.match('text/html')) { 74 | const getRequest = await axios.get(e.url) 75 | const html = getRequest.data 76 | e.title = parse(html).querySelector('title')?.text || e.url 77 | } else { 78 | const fileName = e?.headers['content-disposition']?.match(/(filename=)(")(?.*?)(")/)?.groups?.fileName 79 | e.title = fileName || e.url 80 | } 81 | })) 82 | } 83 | 84 | async postToAPI () { 85 | const jwt = await apiAuth() 86 | await Promise.all(this.sources.map(async e => { 87 | await axios.post(`${process.env.API_URL}/kaynaklars`, { 88 | doc_name: e.title, 89 | doc_link: e.url, 90 | doc_creator_tg: e.tgUser, 91 | doc_tg_ch: e.tgChannel 92 | }, { 93 | headers: { 94 | 'Content-Type': 'application/json', 95 | Authorization: 'Bearer ' + jwt 96 | } 97 | }) 98 | })) 99 | } 100 | } 101 | 102 | module.exports = SourceBot 103 | -------------------------------------------------------------------------------- /src/commands/kontrol.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | 3 | const { apiAuth, errorMessage } = require('../utils') 4 | 5 | async function fetchUnapprovedResources () { 6 | const res = await axios.get(`${process.env.API_URL}/kaynaklars?_limit=99999`) 7 | return res.data.filter(e => !e.approved) 8 | } 9 | 10 | function parseResources (resources) { 11 | if (resources.length) { 12 | return resources.map(e => `*${e.id}:* [${e.doc_name}](${e.doc_link})`).join('\n') 13 | } else { 14 | return '*Tüm kaynaklar onaylandı.*' 15 | } 16 | } 17 | 18 | async function approveResources (ids) { 19 | ids.forEach(async e => { 20 | const jwt = await apiAuth() 21 | console.log(e[0] === '!') 22 | const config = { 23 | url: `${process.env.API_URL}/kaynaklars/${e[0] === '!' ? e.slice(1) : e}`, 24 | method: e[0] === '!' ? 'delete' : 'put', 25 | headers: { 26 | Authorization: `Bearer ${jwt}` 27 | }, 28 | data: { 29 | approved: e[0] !== '!' 30 | } 31 | } 32 | axios(config) 33 | }) 34 | } 35 | 36 | async function kontrolCommand (ctx) { 37 | const args = ctx.message.text.slice(ctx.message.entities[0].length + 1) 38 | try { 39 | if (args) { 40 | await approveResources(args.split(' ')) 41 | await ctx.reply('İşlem başarılı!') 42 | } else { 43 | const resources = await fetchUnapprovedResources() 44 | const parsed = parseResources(resources) 45 | ctx.replyWithMarkdown(`*Onaylanmamış Kaynaklar:*\n\n${parsed}\n\n*Kaynakları onaylamak için:* /kontrol `) 46 | } 47 | } catch (err) { 48 | console.error(err) 49 | ctx.reply(errorMessage() + ' Bir hata oluştu. Lütfen tekrar deneyiniz.') 50 | } 51 | } 52 | 53 | module.exports = kontrolCommand 54 | -------------------------------------------------------------------------------- /src/commands/pin.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | const axios = require('axios') 3 | 4 | const exceptions = fs 5 | .readFileSync('.pinignore') 6 | .toString() 7 | .split('\r\n') 8 | 9 | async function pinCommand (ctx) { 10 | const args = ctx.message.text.slice(ctx.message.text.split(' ')[0].length) 11 | try { 12 | const groupsReq = await axios.get('http://api.eksicode.org/telegrams') 13 | const groups = groupsReq.data 14 | groups.map(async e => { 15 | if (exceptions.includes(e.channelID)) { 16 | console.log(`${e.name} kanalına .pinignore dosyası sebebiyle gönderilmeyecektir.`) 17 | } else { 18 | const message = await ctx.telegram.sendMessage(e.channelID, args, { 19 | disable_notification: true 20 | }) 21 | 22 | ctx.telegram.pinChatMessage( 23 | e.channelID, 24 | message.message_id, 25 | { disable_notification: true } 26 | ) 27 | } 28 | }) 29 | } catch (err) { 30 | console.error(err) 31 | } 32 | } 33 | 34 | module.exports = pinCommand 35 | -------------------------------------------------------------------------------- /src/commands/report.js: -------------------------------------------------------------------------------- 1 | async function reportCommand (ctx) { 2 | const admins = await ctx.telegram.getChatAdministrators(ctx.chat.id) 3 | const out = admins.map(e => `[${e.user.username || e.user.first_name || e.user.last_name}](tg://user?id=${e.user.id})`).join(' ') 4 | ctx.replyWithMarkdown(out) 5 | } 6 | 7 | module.exports = reportCommand 8 | -------------------------------------------------------------------------------- /src/commands/twitter.js: -------------------------------------------------------------------------------- 1 | function twitterCommand (ctx) { 2 | ctx.reply('Twitter hesabımızı takip edin.', { 3 | reply_markup: { 4 | inline_keyboard: [ 5 | [ 6 | { 7 | text: '👉 Twitter Hesabımız', 8 | url: 'https://twitter.com/Eksicode' 9 | } 10 | ] 11 | ] 12 | } 13 | }) 14 | } 15 | 16 | module.exports = twitterCommand 17 | -------------------------------------------------------------------------------- /src/commands/unban.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | const { log } = require('../utils') 3 | 4 | function generateUnbanMessage (ctx, userId) { 5 | const unbanned = `[${userId}](tg://user?id=${userId})` 6 | const admin = `[${ctx.from.first_name || ctx.from.last_name || ctx.from.username}](tg://user?id=${ctx.from.id})` 7 | 8 | return `*${userId}* *UNBAN* ◀️ 🛬\n\n*Banı Açılan Kişi*: ${unbanned}\n*İşlemi Gerçekleştiren Admin*: ${admin}` 9 | } 10 | 11 | async function unbanCommand (ctx, id) { 12 | try { 13 | if (id || (ctx.message.chat.id.toString() === process.env.ADMIN_CH_ID && ctx.message.reply_to_message)) { 14 | const request = await axios.get(`${process.env.API_URL}/telegrams`) 15 | const groups = request.data 16 | 17 | const userId = id || ctx.message.reply_to_message.text.split(' ')[0] 18 | 19 | groups.map(async e => { 20 | await ctx.telegram.unbanChatMember(e.channelID, userId) 21 | }) 22 | await ctx.telegram.sendMessage(process.env.ADMIN_CH_ID, generateUnbanMessage(ctx, userId), { parse_mode: 'Markdown' }) 23 | await log(ctx, { type: 'unban', userId }) 24 | } else { 25 | console.log('Unban Error: Yetkisiz İşlem / Hatalı Kullanım') 26 | } 27 | } catch (err) { 28 | console.log('Unban Error: Yetkisiz İşlem') 29 | console.error(err) 30 | } 31 | } 32 | 33 | module.exports = unbanCommand 34 | -------------------------------------------------------------------------------- /src/commands/youtube.js: -------------------------------------------------------------------------------- 1 | function youtubeCommand (ctx) { 2 | ctx.reply('Youtube kanalımıza abone olun.', { 3 | reply_markup: { 4 | inline_keyboard: [ 5 | [ 6 | { 7 | text: '▶️ Youtube Kanalımız', 8 | url: 'https://www.youtube.com/channel/UCZ6y4r9MMv7jT79FzEn3JxA' 9 | } 10 | ] 11 | ] 12 | } 13 | }) 14 | } 15 | 16 | module.exports = youtubeCommand 17 | -------------------------------------------------------------------------------- /src/handlers/callbackHandler.js: -------------------------------------------------------------------------------- 1 | const { unbanCommand } = require('../commands') 2 | 3 | module.exports = async function (ctx) { 4 | const matchedData = ctx.callbackQuery.data.match(/^(?.+): (?.+)$/).groups 5 | if (matchedData && matchedData.type === 'unban') { 6 | await unbanCommand(ctx, matchedData.data) 7 | await ctx.answerCbQuery() 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/handlers/easterEggHandler.js: -------------------------------------------------------------------------------- 1 | const clean = (piece) => (piece 2 | .replace(/((^|\n)(?:[^\/\\]|\/[^*\/]|\\.)*?)\s*\/\*(?:[^*]|\*[^\/])*(\*\/|)/g, '$1') 3 | .replace(/((^|\n)(?:[^\/\\]|\/[^\/]|\\.)*?)\s*\/\/[^\n]*/g, '$1') 4 | .replace(/\n\s*/g, '') 5 | ); 6 | 7 | const regex = ({raw}, ...interpolations) => ( 8 | new RegExp(interpolations.reduce( 9 | (regex, insert, index) => (regex + insert + clean(raw[index + 1])), 10 | clean(raw[0]) 11 | ), "gmi") 12 | ); 13 | 14 | // Move above to a utils.js or something 15 | 16 | const boomerRegex = regex` 17 | (B|ß) 18 | (o|о|ó|ò|ô|ȯ|ȱ|ö|ȫ|ǒ|ŏ|ō|õ|ȭ|ő|ọ|ǿ|ơ|u|ú|ù|û|ü|ǔ|ŭ|ū|ũ|ű|ů|ụ)+ 19 | (ğ)* 20 | (m)+ 21 | (e|é|è|ė|ê|ë|ě|ĕ|ē|ẽ|e|ẹ|ı|i|í|ì|i|î|ï|ǐ|ĭ|ī|ĩ|ị)+ 22 | (r) 23 | ` 24 | 25 | const jsSartmiRegex = regex`(js [sş]art m[ıi])` 26 | 27 | const iHaveAQuestionRegex = regex`bi(rşey|şey| şey|r şey|şiy| şiy|şi| şi|' şey|'şey) sor(ucam|acağım|acam|cam|ucağım|abilirmiyim|abilir miyim|ammı|am mı|ayım mı|ayımmı)` 28 | 29 | 30 | function jsSartMiHandler (ctx) { 31 | const jsSartMiMatch = ctx.message.text.match(jsSartmiRegex) 32 | const iHaveAQuestionMatch = ctx.message.text.match(iHaveAQuestionRegex) 33 | const boomerMatch = ctx.message.text.match(boomerRegex) 34 | // switch-case? 35 | try { 36 | if (jsSartMiMatch) { 37 | const randomNum = Math.floor(Math.random() * 1000) 38 | if (randomNum > 995) { 39 | ctx.reply('Değil.') 40 | } else { 41 | ctx.reply('Şart.') 42 | } 43 | } else if (iHaveAQuestionMatch) { 44 | ctx.reply('Haydi, sor sor!') 45 | } else if (boomerMatch) { 46 | ctx.reply('Boomer babandır...') 47 | } 48 | } catch (err) { 49 | console.log('unexpected error at easter egg handler.') 50 | }} 51 | 52 | module.exports = jsSartMiHandler 53 | -------------------------------------------------------------------------------- /src/handlers/index.js: -------------------------------------------------------------------------------- 1 | const easterEggHandler = require('./easterEggHandler') 2 | const joinedLeftUserHandler = require('./joinedLeftUserHandler') 3 | const textHandler = require('./textHandler') 4 | const callbackHandler = require('./callbackHandler') 5 | 6 | module.exports = { easterEggHandler, joinedLeftUserHandler, textHandler, callbackHandler } 7 | -------------------------------------------------------------------------------- /src/handlers/joinedLeftUserHandler.js: -------------------------------------------------------------------------------- 1 | function joinedLeftUserHandler (ctx) { 2 | ctx.deleteMessage().catch(err => { 3 | console.log("Hata: Giren/Çıkan kullanıcı handler'ında hata oluştu.") 4 | console.error(err) 5 | }) 6 | } 7 | 8 | module.exports = joinedLeftUserHandler 9 | -------------------------------------------------------------------------------- /src/handlers/textHandler.js: -------------------------------------------------------------------------------- 1 | const cmd = require('../commands') 2 | const { forAdmins } = require('../utils') 3 | const easterEggHandler = require('./easterEggHandler') 4 | 5 | const commands = { 6 | '!kaynak': cmd.SourceBot, 7 | '!grup': cmd.GroupBot, 8 | '!yardim': cmd.helpCommand, 9 | '!help': cmd.helpCommand, 10 | '!discord': cmd.discordCommand, 11 | '!duyuru': cmd.announcementCommand, 12 | '!youtube': cmd.youtubeCommand, 13 | '!twitter': cmd.twitterCommand, 14 | '!github': cmd.githubCommand, 15 | '!report': cmd.reportCommand, 16 | '!hastebinize': cmd.hastebinizeCommand 17 | } 18 | 19 | const adminOnly = [ 20 | '!hastebinize' 21 | ] 22 | 23 | function textHandler (ctx) { 24 | const message = ctx.message.text 25 | const command = message.split(' ')[0] 26 | if (command in commands) { 27 | if (adminOnly.includes(command)) { 28 | return forAdmins(ctx, commands[command]) 29 | } else { 30 | try { 31 | return new commands[command](ctx) 32 | } catch (e) { 33 | return commands[command](ctx) 34 | } 35 | } 36 | } else { 37 | return easterEggHandler(ctx) 38 | } 39 | } 40 | 41 | module.exports = textHandler 42 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const handlers = require('./handlers') 2 | const cmd = require('./commands') 3 | const utils = require('./utils') 4 | 5 | module.exports = { cmd, handlers, utils } 6 | -------------------------------------------------------------------------------- /src/utils/apiAuth.js: -------------------------------------------------------------------------------- 1 | const axios = require('axios') 2 | 3 | async function apiAuth () { 4 | try { 5 | const res = await axios.post(`${process.env.API_URL}/auth/local`, { 6 | identifier: process.env.API_USER, 7 | password: process.env.API_PASS 8 | }, { 9 | headers: { 10 | 'Content-Type': 'application/json' 11 | } 12 | }) 13 | 14 | const data = res.data 15 | 16 | return data.jwt 17 | } catch (err) { 18 | console.log('API Yetkilendirmesi esnasında bir hata oluştu.') 19 | console.error(err) 20 | } 21 | } 22 | 23 | module.exports = apiAuth 24 | -------------------------------------------------------------------------------- /src/utils/errorMessage.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | 3 | const hataMesaji = fs 4 | .readFileSync('hataMesaji.txt') 5 | .toString() 6 | .split('\r\n') 7 | 8 | module.exports = () => hataMesaji[Math.floor(Math.random() * hataMesaji.length)] 9 | -------------------------------------------------------------------------------- /src/utils/forAdmins.js: -------------------------------------------------------------------------------- 1 | async function forAdmins (ctx, cb) { 2 | try { 3 | const check = await ctx.telegram.getChatMember( 4 | process.env.ADMIN_CH_ID, 5 | ctx.from.id 6 | ) 7 | if (check && check.status !== 'kicked' && check.status !== 'left') { 8 | return cb(ctx) 9 | } 10 | } catch (e) { 11 | console.error(e) 12 | } 13 | } 14 | 15 | module.exports = forAdmins 16 | -------------------------------------------------------------------------------- /src/utils/hastebinize.js: -------------------------------------------------------------------------------- 1 | const fetch = require('node-fetch'); 2 | 3 | // Will turn `text` into a hastebin document. 4 | // Should return a Hastebin URL. 5 | 6 | async function hastebinize(text) { // Message.reply_to_message.text as argument. 7 | try { 8 | const requestToHastebin = await fetch('https://hastebin.com/documents', { // POSTs message to hastebin. Should return an object 9 | method: 'POST', // that contains hastebin document id. 10 | body: text // Example: {key: 'ezuhusunaq'} 11 | }) 12 | 13 | const response = await requestToHastebin.json() 14 | 15 | return `https://hastebin.com/${response?.key}` 16 | 17 | } catch (err) { 18 | return err 19 | } 20 | } 21 | 22 | module.exports = hastebinize -------------------------------------------------------------------------------- /src/utils/index.js: -------------------------------------------------------------------------------- 1 | const apiAuth = require('./apiAuth') 2 | const errorMessage = require('./errorMessage') 3 | const forAdmins = require('./forAdmins') 4 | const log = require('./log') 5 | const hastebinize = require('./hastebinize') 6 | 7 | module.exports = { apiAuth, errorMessage, forAdmins, log, hastebinize } 8 | -------------------------------------------------------------------------------- /src/utils/log.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs') 2 | 3 | function parseLog (ctx, date, event) { 4 | const chat = `${ctx.chat.title} (${ctx.chat.id})` 5 | const time = `${ 6 | (date.getHours() + "").padStart(2, "0") 7 | }:${ 8 | (date.getMinutes() + "").padStart(2, "0") 9 | }:${ 10 | (date.getSeconds() + "").padStart(2, "0") 11 | } UTC` 12 | if (event === 'ban') { 13 | console.log("selam") 14 | const banned = ctx.message.reply_to_message.from 15 | const admin = ctx.from 16 | const reason = ctx.message.text.slice(ctx.message.entities[0].length + 1) 17 | const bannedParsed = `${banned.first_name || banned.last_name || banned.username} (${banned.id})` 18 | const adminParsed = `${admin.first_name || admin.last_name || admin.username} (${admin.id})` 19 | 20 | return `[BAN] ${time} - ${bannedParsed} - ${adminParsed} - ${reason || "No reason"}\n` 21 | } else if (event?.type === 'unban') { 22 | const unbanned = `${event.userId}` 23 | const admin = `${ctx.from.first_name || ctx.from.last_name || ctx.from.username} (${ctx.from.id})` 24 | 25 | return `[UNBAN] ${time} - ${unbanned} - ${admin}\n` 26 | } 27 | if (ctx.message) { 28 | const text = ctx.message?.text || 'ATTACHMENT ONLY' 29 | const user = ctx?.from 30 | const userParsed = `${user.first_name || user.last_name || user.username} (${user.id})` 31 | 32 | if (ctx.message.new_chat_members) { 33 | return ctx.message.new_chat_members.map(user => { 34 | const userParsed = `${user.first_name || user.last_name || user.username} (${user.id})` 35 | return `[NEW MEMBER] ${time} - ${chat}: ${userParsed}` 36 | }).join('\n') + '\n' 37 | } else if (ctx.message.left_chat_member) { 38 | const user = ctx.message.left_chat_member 39 | const userParsed = `${user.first_name || user.last_name || user.username} (${user.id})` 40 | return `[LEFT MEMBER] ${time} - ${chat}: ${userParsed}\n` 41 | } else { 42 | return `[MESSAGE] ${time} - ${chat} - ${userParsed}: ${text}\n` 43 | } 44 | } 45 | } 46 | 47 | async function log (ctx, event) { 48 | try { 49 | const date = new Date() 50 | const fileName = `logs/log_${date.getDate()}-${date.getMonth() + 1}-${date.getFullYear()}.txt` 51 | fs.appendFile(fileName, parseLog(ctx, date, event), (err) => { 52 | if (err) throw err 53 | }) 54 | } catch (err) { 55 | console.error(err) 56 | } 57 | } 58 | 59 | module.exports = log 60 | -------------------------------------------------------------------------------- /telegram.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | require('dotenv').config({ 3 | path: path.join(__dirname, '.env') 4 | }) 5 | const { Telegraf } = require('telegraf') 6 | const bot = new Telegraf(process.env.BOT_TOKEN) 7 | const axios = require('axios') 8 | const { apiAuth } = require('./src/utils') 9 | const cron = require('node-cron') 10 | 11 | const sleep = (ms) => { 12 | return new Promise(resolve => setTimeout(resolve, ms)) 13 | } 14 | 15 | /** 16 | * Cron Job 17 | * 18 | * Run crone job everyday 19 | * 20 | * @param '00 01 * * *' Evertyday will backup at 01 21 | */ 22 | 23 | cron.schedule('00 01 * * *', async () => { 24 | // cron.schedule('1 * * * * *', async () => { 25 | console.log('Eksicode User Counts Checking Started') 26 | console.log('-----------------------------------------') 27 | 28 | const jwt = await apiAuth() 29 | 30 | // Update group members 31 | const updateMembers = async (id, members) => { 32 | try { 33 | const requestData = { 34 | members: members 35 | } 36 | const config = { 37 | headers: { 38 | 'Content-Type': 'application/json', 39 | Authorization: 'Bearer ' + jwt 40 | } 41 | } 42 | axios.put(`${process.env.API_URL}/telegrams/` + id, requestData, config) 43 | .catch(err => { 44 | console.log(err) 45 | }) 46 | } catch (err) { 47 | console.error(err) 48 | } 49 | } 50 | 51 | let allGroups 52 | 53 | // Get group list from api 54 | axios.get(`${process.env.API_URL}/telegrams?_sort=ListOrder:ASC`) 55 | .then(async function (response) { 56 | allGroups = response.data 57 | }) 58 | .then(async () => { 59 | console.log('total groups: ' + allGroups.length) 60 | 61 | // Get group member count from Telegram 62 | for (let i = 0; i < allGroups.length; i++) { 63 | await bot.telegram 64 | .getChatMembersCount(allGroups[i].channelID) 65 | .then(data => { allGroups[i].members = data }) 66 | .then(async () => { 67 | console.log(allGroups[i].name, allGroups[i].members + ' user') 68 | await sleep(2000) 69 | updateMembers(allGroups[i].id, allGroups[i].members) 70 | 71 | console.log(allGroups[i].name + ' Uptated...') 72 | console.log('-------------------------') 73 | }) 74 | .catch(err => { 75 | console.log(`${allGroups[i].name} wasn't respond any date.`) 76 | console.log(err) 77 | }) 78 | 79 | delete allGroups[i].channelID 80 | } 81 | }) 82 | .then(() => { 83 | console.log('Eksicode User Counts Checking finished') 84 | console.log('-----------------------------------------') 85 | }) 86 | .catch((err) => { 87 | console.log(err) 88 | }) 89 | }) 90 | -------------------------------------------------------------------------------- /telegram_func.js: -------------------------------------------------------------------------------- 1 | const path = require('path') 2 | 3 | require('dotenv').config({ 4 | path: path.join(__dirname, '.env') 5 | }) 6 | 7 | const { Telegraf } = require('telegraf') 8 | const bot = new Telegraf(process.env.BOT_TOKEN) 9 | 10 | const { cmd, utils, handlers } = require('./src') 11 | 12 | bot.use(async (ctx, next) => { 13 | await utils.log(ctx) 14 | await next() 15 | }) 16 | 17 | bot.command('ban', ctx => utils.forAdmins(ctx, cmd.banCommand)) 18 | bot.command('unban', ctx => utils.forAdmins(ctx, cmd.unbanCommand)) 19 | bot.command('pin', ctx => utils.forAdmins(ctx, cmd.pinCommand)) 20 | bot.command('kontrol', ctx => utils.forAdmins(ctx, cmd.kontrolCommand)) 21 | bot.command('yardim', ctx => cmd.helpCommand(ctx)) 22 | bot.command('help', ctx => cmd.helpCommand(ctx)) 23 | 24 | bot.on(['new_chat_members', 'left_chat_member'], ctx => handlers.joinedLeftUserHandler(ctx)) 25 | 26 | bot.on('text', ctx => handlers.textHandler(ctx)) 27 | 28 | bot.on('callback_query', handlers.callbackHandler) 29 | 30 | bot.launch() 31 | --------------------------------------------------------------------------------