1.3.8 • Published 3 years ago

duagram v1.3.8

Weekly downloads
-
License
-
Repository
github
Last release
3 years ago

duaGram

Telegram Framework for userbot and or bot api, using nodejs.

GitHub last commit GitHub release (latest by date) npm node-current GitHub code size in bytes GitHub repo size Lines of code GitHub top language GitHub all releases GitHub Discussions npm GitHub pull requests GitHub issues

duagram

GitHub watchers GitHub forks GitHub Repo stars

WARNING!

Use at Your Own Risk.

I don't take any responsibility from actions made by you or on your account.

History

Support

  • Issues
  • Contributor are welcome...

Install

npm i duagram

or

yarn add duagram

or

pnpm add duagram

Quick Start

const { duaGram } = require("duagram");

const bot = new duaGram({
    api_id: 1,
    api_hash: 'your-api-hash',
    // Fill in the session here if you have one, or leave it blank
    session: '', 
});

bot.cmd('ping', (ctx) => {
    console.log(ctx);
    // bot.sendMessage(ctx, 'pong'); // or:
    // bot.sendMessage(ctx.chat.id, 'pong'); // or:
    return ctx.reply('pong!');    
});

bot.start();

API TELEGRAM

To use the duaGram, you first have to get API ID dan API HASH.

Get it from https://my.telegram.org

Token Bot

If you connect use Bot API, get a bot account by chatting with BotFather.

BotFather will give you a token, something like 123456789:AbCdfGhIJKlmNoQQRsTUVwxyZ.

More Example

Do you need more example? Check this page.

User Login

const { duaGram, terminal } = require("duagram");

const bot = new duaGram({
    api_id: 1,
    api_hash: 'your-api-hash',

    logLevel: 1, // 0 false, 1 event, 2 detail
    logDetail: "none", // none, error, warn, info, debug

    // Fill in the session here if you have one, or leave it blank
    session: '', 

    // The most common error is the FloodWait error which is caused by calling a method multiple times in a short period and acts as a spam filter from telegram. So:
    floodSleepThreshold: 120, 

    // Mark message history as read
    markRead: false 
});

bot.on('message', (ctx, _ctx) => {
    terminal.debug('Ctx Duagram');
    console.log(ctx);
});

bot.cmd('ping', (ctx) => {
    bot.sendMessage(ctx, 'Pong!', { replyToMsgId: ctx.id });
});

bot.cmd('upload', async (ctx) => {
    terminal.info('Starting upload...');
    let file = './photo.jpg';
    return bot.sendFile(ctx.chat.id, file);

});

bot.cmd('version', (ctx) => {
    return bot.sendMessage(ctx, `<code>${JSON.stringify(bot.version, null, 2)}<code>`, { parse_mode: 'HTML' });
});

bot.start();

Bot Login

Login with Bot API Token

const { duaGram, terminal, Helper } = require("duagram");

const bot = new duaGram({
    api_id: 1,
    api_hash: 'your-api-hash',
    as_bot_api: true,
    bot_token: 'your-token-bot'
});

// event all new message
bot.on('message', async (ctx) => {
    terminal.debug('Ctx Duagram');
    console.log(ctx);
});

bot.cmd('ping', (ctx) => {
    return ctx.reply('Pong!', { replyToMsgId: ctx.id });
});

bot.cmd('upload', async (ctx) => {
    terminal.info('Starting upload...');
    let file = './photo.jpg';
    return await bot.sendFile(ctx.chat.id, file);

});

// bot API
bot.cmd('start', async (ctx) => {
    // message in only
    if (ctx.out) return false;

    if (!bot.asBotApi) {
        return bot.sendMessage(ctx, "I'm not bot api 😅")
    }

    let chat_id = ctx.chat.id;
    if (ctx.chat.type == 'channel') {
        chat_id = bot.Helper.chat.to_api(chat_id);
    }

    // if Bot API, send with Bot API can too
    let reply_markup = JSON.stringify({
        inline_keyboard: [
            [
                bot.Helper.Button.url('👥 uBotIndonesia', 'https://t.me/ubotindonesia')
            ], [
                bot.Helper.Button.text('One', 'cb1'),
                bot.Helper.Button.text('Two', 'cb2')
            ]
        ]
    });

    let more = {
        parse_mode: 'html',
        reply_markup
    }

    return bot.BotApi.sendMessage(chat_id, 'This message from <b>Bot Api</b>', more)
        .then(result => {
            terminal.log('Result: BotApi sendMessage')
            console.log(result);
        })
        .catch(error => terminal.error(error.message));
});

bot.cmd('version', (ctx) => {
    return bot.sendMessage(ctx, `<code>${JSON.stringify(bot.version, null, 2)}<code>`, { parse_mode: 'HTML' });
});

bot.start();

Documentation

duaGram

Session

Options

const bot = new duaGram(options);

ItemDescriptionDefault
api_idget it from https://my.telegram.org
api_hashget it from https://my.telegram.org
sessionsession string
session_nameSession name-
localwith local databasefalse
logLevelShow log level 0 off, 1 event name, 2 detail1
logDetailEvent Detail (none, error, warn, info, debug)info
as_bot_apiLogin as bot API? 0 false / 1 true0
bot_tokenToken Bot API @botfahter
connectionRetriesConnection Retry3
floodSleepThresholdFloodWait error ? Set this120
markReadMark message history as readTRUE
cmdPrefixprefix for command trigger!/.

Event

Available :

  • on(updateType, stop=true)
  • cmd(string, callback, stop=true)
  • hear(regex|string, callback, stop=true)
  • hears(regex|string, callback, stop=true) alias hear
  • command alias cmd

Example:

bot.cmd('ping', callback);
bot.hear('hello', callback);
bot.hear(/^!time$/i, callback);

bot.hear(/coffee/i, callback, false); // if found stopable? false. So, catch condition anatoher again bellow
bot.hear(/tea/i, callback);

Update Type

Example:

bot.on('message', (ctx, _ctx) => terminal.less(ctx) );

Available:

  • connected
  • raw
  • message
  • media
  • all class names in mtproto, according to the log details

You can see on ctx.event message too.

Class name event example:

  • UpdateNewMessage
  • UpdateShortMessage
  • UpdateReadHistoryOutbox
  • UpdateDeleteMessages
  • UpdateUserTyping
  • etc... schema

Result object raw without middleware effect.

Properties

Method or Accessors of duaGram.

methoddescription
telegramcollection function duagram
Apiaccess for API Telegram
clientclient connecton
BotApiwrapper for Bot Api Telegram
terminalconsole replacement for colorful and bettermore
lessLogbetter thanconsole.log function, less prefix _ field
asBotApitrue/false
versionduagrams version info
cmdPrefixdefault is.!/
HelperGo to helper doc

Example:

const bot = new duaGram({...});

bot.cmdPrefix = '~'; // bot.cmd('ping', ..) => ~ping
console.log(bot.version);

Alias

  • tg (alias telegram)
  • invoke(params)
  • sendMessage(peer, text, more)
  • ... etc (like telegram method)

Telegram

method

  • invoke(params)
  • getPeerId(ctx)
  • sendMessage(peer, text, more)
  • editMessage(peer, id, text, more)
  • deleteMessages(peer, ids, more)
  • forwardMessages(peerFrom, peerTo, ids, more)
  • getMessages(peer, ids)
  • pinMessage(peer, id, more)
  • unpinAllMessages(peer)
  • readHistory(peer, more)
  • getUserPhotos(peer, more)
  • getUserInfo(peer)
  • editAdmin(peerChatId, peerUserId, more = {})
  • editBanned(peerChatId, peerUserId, more = {})
  • joinGroup(peer)
  • readMentions(peer)
  • readMessageContents(id)
  • deleteHistory(peer, more)
  • deleteUserHistory(channelId, userId)

Middleware

Middleware is an essential part of any modern framework. It allows you to modify requests and responses as they pass between the Telegram and your bot.

You can imagine middleware as a chain of logic connection your bot to the Telegram request.

Middleware normally takes two parameters (ctx, next), ctx is the context for one Telegram update, next is a function that is invoked to execute the downstream middleware. It returns a Promise with a then function for running code after completion.

bot.middleware((ctx, next) => {
    ctx.additional = 'message test from middleware';
    next();
});

bot.cmd('plus', async (ctx) => {   
    if (!ctx.out)
        return bot.sendMessage(ctx.chat.id, `Hooked: ${ctx.additional}`);
})

Middleware List

Middleware more information: click here.

client

Method

  • start()
  • checkAuthorization()
  • signInUser()
  • signInUserWithQrCode()
  • signInWithPassword()
  • inlineQuery()
  • buildReplyMarkup()
  • downloadFile()
  • downloadProfilePhoto()
  • downloadMedia()
  • setParseMode()
  • iterMessages()
  • getMessages()
  • sendMessage()
  • forwardMessages()
  • editMessage()
  • iterDialogs()
  • getDialogs()
  • iterParticipants()
  • getParticipants()
  • removeEventHandler()
  • listEventHandlers()
  • uploadFile()
  • sendFile()
  • invoke()
  • getMe()
  • isBot()
  • isUserAuthorized()
  • getInputEntity()
  • getPeerId()
  • connect()
  • getDC()
  • disconnect()
  • destroy()
  • ... etc

Reference

Last Words

Happy nge-bot!

If you are Indonesian, let's join the @ubotindonesia telegram group.

see you again ^^

1.3.8

3 years ago

1.3.7

3 years ago

1.3.6

3 years ago

1.3.5

3 years ago

1.3.4

3 years ago

1.3.3

3 years ago

1.3.2

3 years ago

1.3.1

3 years ago

1.3.0

3 years ago

1.2.8

3 years ago

1.2.7

3 years ago

1.2.30

3 years ago

1.2.31

3 years ago

1.2.9

3 years ago

1.2.6

3 years ago

1.2.5

3 years ago

1.2.4

3 years ago

1.2.3

3 years ago

1.2.2

3 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.5

3 years ago

1.1.2

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago

0.0.1

3 years ago