Unhandled error while processing telegraf

Unhandled error while processing update #13 Comments I am deploying my bot on AWS lamda using serverless framework that’s why I am using telegraf-aws module. The webhook gets triggered when I send message to the bot but it ends up in an error. The code looks very simple but still not working. Here is […]

Содержание

  1. Unhandled error while processing update #13
  2. Comments
  3. Footer
  4. How to handle errors #486
  5. Comments
  6. Telegraf Crashes When replyWithPhoto Is Used with Webhook #440
  7. Comments
  8. Context
  9. Expected Behavior
  10. Current Behavior
  11. Failure Information (for bugs)
  12. Failure Logs
  13. sendVideo failed, reason: socket hang up #581
  14. Comments
  15. Context
  16. Expected Behavior
  17. Failure Logs
  18. Unhandled error while processing telegraf
  19. Context
  20. Expected Behavior
  21. Current Behavior
  22. Steps to Reproduce
  23. Error Message: Type ‘FmtString’ is not assignable to type ‘string’.
  24. Context
  25. Minimal Example Code Reproducing the Issue
  26. tsconfig.json file below
  27. UPDATE
  28. Context
  29. Minimal Example Code Reproducing the Issue
  30. Expected Behavior
  31. Current Behavior
  32. Additional
  33. Context
  34. Expected Behavior
  35. Current Behavior
  36. Failure Information (for bugs)
  37. Steps to Reproduce
  38. Context
  39. Minimal Example Code Reproducing the Issue
  40. Expected Behavior
  41. Current Behavior
  42. Error Message and Logs ( export DEBUG=’telegraf:*’ )
  43. Discussed in #1756

Unhandled error while processing update #13

I am deploying my bot on AWS lamda using serverless framework that’s why I am using telegraf-aws module.

The webhook gets triggered when I send message to the bot but it ends up in an error.

The code looks very simple but still not working. Here is my code:

And here is the error

Please help. Thanks

The text was updated successfully, but these errors were encountered:

This doesn’t seem to be a problem with telegram-keyboard . If you do console.log(mainMenuKeyboard) you will see that reply_markup looks good. Does this error appear if you remove the use of telegram-keyboard ? And what version of Telegraf?

I figured it out. It wasn’t really a problem with telegram-keyboard . I am new in nodejs world so I think I made a funny mistake. Anyway I changed my code a little bit and it worked 🙂

I would appreciate if you educate me what makes it different from the previous one.

PS I am a java developer who just started learning nodejs 🙂

I just copy pasted the code from examples in this repository. I think you might want to update that file as well.

I could explain the reason if I wrote better in English 😄
But now I see that you are using telegraf@4.x version. So, in telegraf@4.x you cannot be destructured methods from context (you must always write like this: (ctx) => ctx.reply(‘some’) . My examples written for telegraf@3.x where you can write as you like, for example (< reply >) => reply(‘some’)

I recommend using telegraf@3.38.0 because version 4 is currently unstable

install using npm

Thank you so much for pointing me to right direction 🙂
But I can’t understand why we can’t use destructing in latest version ?

When destructuring a method from the class, its execution context is lost and this is no longer referenced to the current instance. And in this line https://github.com/telegraf/telegraf/blob/develop/src/context.ts#L264 this is equal undefined

You can play around with this small example to figure out what’s the matter

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

How to handle errors #486

I’m currently doing a little project using Telegraf and I have a problems handling errors. I have read a lot about it and I have seen some solutions but they are not working.

The code I am having problems with is basically this one:

And, for example, when I open another bot I have this problem, very reported:
Failed to process updates. < Error: 409: Conflict: terminated by other getUpdates request

I have seen that you can use bot.catch(err => console.log(err)); but it’s not working for me. As I know, Telegraf works with promises, so I also tried bot.startPolling().catch(err => console.log(err));

I’m sorry it this have been answered already, as you can see I did some research but nothing is working because I’m missing something.

The text was updated successfully, but these errors were encountered:

I have another bot running in Python and I know that with Telepot (The python framework for Telegram) it has a loop trying to reconnect, but here the process stops suddenly.

I’m going to try it as soon as I can. Thank you.

Tried. Useful to work with promises but the problem is the same one:

And what do you want?

To auto reconnect after this kind of conflict, leaving it as a warning or something like that

Use try/catch or .catch() for it.

That is the same answer than the first one. The problem does not appear processing the message, the problem is caused by the getUpdates process. That it’s what I want to catch.

But you sad the problem caused by getUpdates. Why are you catching it in startPolling? Btw, it is not async function.

So if you remove the process_message, does error gone away?

const bot = new Telegraf(config.telegram.token);
bot.startPolling();

This code raises the same error. I think that getUpdates is the function that launch the event ‘on message’, so I can not catch it by catching bot.on

Why don’t I have it? Maybe it’s your environment issue? Check out things like a firewall and so on.

It happens when two bots are running at the same time. You can force it consulting the API while the bot is on work. Try it:

Probably only one bot can do it?

Yeah, it can. But it is a security check. What if someone else starts another bot with the same token or you use the same token on development and production?

You have to be sure that your server ia not going to stop working because of a little mistake.

I finally decided to edit the bot to add the option to reconnect after the 409 error. You can take a look to it here: #494

As I said, that does not work because I am dealing with a very specific error that does not throw anything.

@msolefonte is it possible to run multiple telegraf clients on the same bot? For instance, in a cluster scenario, each node would require a telegraf client that have access to the same bot.

can anyone tell me how fix this error.
[] Service: facebook
[
] Checking if username exists.
Traceback (most recent call last):
File «/usr/local/bin/brut3k1t», line 11, in
load_entry_point(‘brut3k1t==3.0.1’, ‘console_scripts’, ‘brut3k1t’)()
File «build/bdist.linux-x86_64/egg/brut3k1t/main.py», line 89, in main
File «build/bdist.linux-x86_64/egg/brut3k1t/web.py», line 47, in execute
File «build/bdist.linux-x86_64/egg/brut3k1t/web.py», line 56, in usercheck
File «/usr/lib/python2.7/dist-packages/selenium/webdriver/firefox/webdriver.py», line 164, in init
self.service.start()
File «/usr/lib/python2.7/dist-packages/selenium/webdriver/common/service.py», line 83, in start
os.path.basename(self.path), self.start_error_message)
selenium.common.exceptions.WebDriverException: Message: ‘geckodriver’ executable needs to be in PATH.

What did you do to get it? And how is it relating to the telegraf?

Try to put the geckodriver executable to your PATH variable. Just like it written in the error.

@rndlaine try to connect your cluster to one telegraf instance, just like you wanted to connect a few telegraf clients to a bot.

Lol I don’t know how scaling of Node.js works in your world, but in mine I use pm2 that runs multiple node instances plus several physical hosts thats comes out with 12 parallel node instances minimum. All of them running the same code and sharing the same telegram bot token. And ultimately expected that after running u momentally get this error:

Failed to process updates. TelegramError: 409: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running

Dear telegram and telegraph, I don’t need to make sure, I completely sure that I run multiple instances and I will not left only one!

@msolefonte I completely agree with your problem. It turns out that Telegraph needs to be finalized to become production-ready

Источник

Telegraf Crashes When replyWithPhoto Is Used with Webhook #440

Context

  • Telegraf.js Version: 3.21.2
  • Node.js Version: v10.3.0
  • Operating System: Ubuntu 18.04 LTS

Expected Behavior

I have a simple bot, which replies with image to any text received. Basically, everything it does is

Everything works just fine when the bot is configured to use polling, but crashes if I set up webhook.

Current Behavior

When I configure the bot to use webhook, it crashes when I try to send a photo with ctx.replyWithPhoto. If I modify the code above to:

everything works. So basically, telegraf crashes when photo is being sent with answerToWebhook.

Failure Information (for bugs)

Failure Logs

The text was updated successfully, but these errors were encountered:

Hello @kaliway, check #320 issue

When you use webhook, telegraf use webhookReply to answer by default. That hold http socket opened while your promise performed.

If you wanna make more replies, you should use Promise chaining, smth like ctx.reply().then(() => ctx.reply()).then(()=> ctx.reply. ).
Or you can disable webhookReply in config: new Telegraf(BOT_TOKEN, < webhookReply: false>);

Thanks, but the thing is, I only have one reply in my code and telegraf crashes:

Basically, the following code crashes telegraf:

when webhookReply is true. I believe this is obviously a bug.

Surprisingly, if I use the following code:

Everything works fine, possibly because ctx.reply(someMessage) goes via webhookReply, while ctx.replyWithPhoto does not. I suspect uploading and sending photos via webhookReply is somehow broken.

By the way, I see no reason why I need to use promise chaining when sending multiple messages. If I don’t mind the order, everything should work just fine in parallel.

const bot = new Telegraf(process.env.BOT_TOKEN, ) does not help either.

There is a complete script, which illustrates the problem:

When I send /start everything works just fine.
When I send any text, bot crashes with the following output:

Hmm, if problem is in sending photo, try to don’t use file stream
Mb you just need to specify path to image
check #395

tva10 I appreciate your effort to help, but I am not really interested in finding a workaround for the problem. I filed this bug report just to let the community and the developers know that some pretty basic functionality is broken.

OK, finally it looks like I found the cause for the issue.

The solution is to simply change the code:

There is a perfectly valid reason for this change, though. The code in webhook.ls expects a Promise. When the Promise is resolved, the response is ended. If return is omitted, no promise to wait is received and the response is ended before the response body is fully written.

Basically, the bug is in my code. However, I do think that there is a documentation issue. If you take a look at the Working with files section from which I copied the code, there is no return in the example there. On the other hand, return is used in other parts of documentation. So the documentation kinda sends mixed messages 🙂 I believe it should be clearly stated somewhere in the documentation that using return is a must.

Источник

sendVideo failed, reason: socket hang up #581

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Telegraf.js Version: 3.26.0
  • Node.js Version: v10.15.0
  • Operating System: Linux raspberrypi 4.14.79-v7+

Expected Behavior

I’d like to send short video from bot to user.
It worked some time ago using bot with connection through HTTP proxy (due to Russiam limitations), but now, with SOCKS5 proxy it doesn’t.

const Telegraf = require(‘telegraf’);
const SocksAgent = require(‘socks5-https-client/lib/Agent’);
const socksAgent = new SocksAgent( <
socksHost: ‘host’,
socksPort: port,
socksUsername: ‘user’,
socksPassword: ‘password’,
>);
const bot = new Telegraf(‘token’, <
telegram: < agent: socksAgent >
>);

bot.hears(‘hi’, (ctx) => ctx.reply(‘Hey there’))
bot.on(‘sticker’, (ctx) => ctx.reply(‘ 👍 ‘))
bot.command(‘video’, (ctx) => <
ctx.replyWithVideo(< source: file >);
logger.log(‘info’, ‘video — %s’, file );
>

Failure Logs

Please include any relevant log snippets or files here.

Bot works Ok for text messages, but keeps silent for for stickers.

hi
Hey there
😐
Silent
/video
Silent

info: Access <«meta»:[«USER»,» with a command «,»hi»]>
info: Response time 640ms
info: Access <«meta»:[«USER»,» with a command «,» 😐 «]>
info: Response time 2ms
info: Access <«meta»:[«USER»,» with a command «,»/video»]>
info: video — 11-01-2019__13-33-10.mp4
info: Response time 166ms

(node:8453) UnhandledPromiseRejectionWarning: FetchError: request to https://api.telegram.org/botTOKEN/sendVideo failed, reason: socket hang up
at ClientRequest. (/node_modules/node-fetch/lib/index.js:1345:11)
at ClientRequest.emit (events.js:187:15)
at Socks5ClientSocket.socketOnEnd (_http_client.js:426:9)
at Socks5ClientSocket.emit (events.js:187:15)
at TLSSocket. (/home/pi/node_modules/socks5-client/lib/Socket.js:146:8)
at TLSSocket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1094:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:8453) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:8453) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The text was updated successfully, but these errors were encountered:

Источник

Unhandled error while processing telegraf

Missing message_thread_id for forwardMessage in Context after 1b73d33

Maybe need to add with future Bots API 6.4

Created at 1 week ago

Is there a way to get the date and time of a message being sent from user?
Locale would be the best (including the Time zone).

Created at 1 week ago

Is your feature request related to a problem? Please describe.
I am trying to pass an array of string as Trigger Type (Params Type) for bot.action but I didn’t get any response .

Describe the solution you’d like
What can be done to make my code in Screenshot run?

To be line this :

But the code in Screenshot is not working , there is no response.

What can be done to make my code in Screenshot run?

Created at 1 week ago

How do I change the scene for a user without context?

For example: if the user does not write to the bot during some time, to enter the scene without context / messages from him and call the first scene, which will send him a message and will wait for a response. Or how i can save context, for after call enter scene?

Created at 1 week ago

Context

I get an error when trying to sendDocument over 200mb size.

Expected Behavior

I need to send files over 200mb size.

Current Behavior

Steps to Reproduce

Created at 1 week ago

Error Message: Type ‘FmtString’ is not assignable to type ‘string’.

Context

  • Telegraf.js Version:»^4.11.2″
  • Node.js Version: 18.12.1
  • Operating System: windows 11
  • TS version : «^4.9.3»

Minimal Example Code Reproducing the Issue

tsconfig.json file below

UPDATE

Fmtstring doesn’t support for the InlineQueryResult[] 🤔

Refferences

Created at 1 week ago

Describe the solution you’d like
Please write proper docstrings for the methods that exist in this library.
Like return types, input parameters and also usage scenarios.

Created at 2 weeks ago

Context

  • Telegraf.js Version: 4.11.2
  • Node.js Version: 16.13.0
  • Operating System: Windows

Minimal Example Code Reproducing the Issue

Expected Behavior

This was supposed to move on to the next prompt after the user entering the target language

Current Behavior

Stuck inside a loop prompting the user again and again for the target language

Additional

When I looked at the internal implementation of bot.on() it has I think a conflicting namespace.

`
on >(
filters: MaybeArray,
. fns: NonemptyReadonlyArray >>
): this

  • Registers middleware for handling updates narrowed by update types or message subtypes.
  • @deprecated Use filter utils instead. Support for Message subtype in Composer::on will be removed in Telegraf v5.

on (
filters: MaybeArray,
. fns: NonemptyReadonlyArray >
>
): this

on >(
filters: MaybeArray,
. fns: NonemptyReadonlyArray
: Filter extends tt.UpdateType | Guard
? FilteredContext
: never
>
>
): this <
// @ts-expect-error This should get resolved when the overloads are removed in v5
return this.use(Composer.on(filters, . fns))
>
`

In my scenario it is using the deprecated version of it!

Created at 2 weeks ago

Hey there
i want to edit both message an inline keyboard when any button pressed
i want to change to for example 7up and fanta
how could i do that?
thanks

Created at 2 weeks ago

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Telegraf.js Version: using the develop branch
  • Node.js Version: 15.0.1
  • Operating System: Arch

Expected Behavior

it’s supposed to enter the scene

Current Behavior

Telling me that ctx.scene.enter(«scene_name») is not a function.

Failure Information (for bugs)

TypeError: Cannot read property ‘enter’ of undefined

Steps to Reproduce

  1. Define a wizard scene
  2. Define a stage scene with that wizard scene as an argument
  3. Define the telegraf instance
  4. launch telegraf, use the stage middleware ( stage.middleware() )
  5. telegraf.command(«test», ctx=>ctx.scene.enter(«scene_name»))

is this the correct way to enter a scene in the first place?

Created at 3 weeks ago

I want the bot to read and store what a user says after the bot’s message. Example:

Bot: Insert BTC Wallet Address for the payment
User: 489tyh34078fgh7g4q3t03y3

The 489tyh34078fgh7g4q3t03y3 needs to gets stored in a variable, but I have not Idea how can make the bot read that

Created at 4 weeks ago

Context

I found potential bug in wizard scenes, certain time ago, one guy in other Telegraf chat tried to enter from wizard scene to wizard scene, and cursor has not been reset.

I tried to reproduce this bug, and it exists

  • Telegraf.js Version: 4.11.2, 4.0.3, 3.40
  • Node.js Version: 16
  • Operating System: Ubuntu

Minimal Example Code Reproducing the Issue

I try some this:

But it doesn’t work too (not surprising, leave by default called in enter)

Expected Behavior

Current Behavior

Error Message and Logs ( export DEBUG=’telegraf:*’ )

Created at 4 weeks ago

The message property of ctx has a lot of missing type definitions which don’t follow the official ones.

The line of code causing the error was this one:
bot.on(«message», (ctx) => ctx.reply(ctx.message.text));
The bot should reply with the text you send to him.

Created at 1 month ago

My scenario is as follows:
I have a /configure command that needs to do a slow request in the background(lets say 30-60 seconds)
I want /configure to return a ctx.reply() and then block until the slow request is done

Here is a sample code:

The Issue
Telegram does not send any other webhook event (for example running /configure command again, while the first /configure is running).

I was under the impression that when setting webhookReply = true , the first ctx.reply() will tell Telegram that the update was handled, and I will be able to receive other commands even though my lambda didn’t finish yet (#1167).

What am I missing?

Note
I know I can schedule this request using an SQS event or something and exit from the lambda as-soon-as-possible.
However, I would like to know if I understood webhookReply correctly as it sounds like this is its exact purpose

Created at 1 month ago

Discussed in #1756

Originally posted by kapisolec December 6, 2022
Hello, I would like to ask is there a way to globally catch all the errors regarding requests/responses that Telegram sends? I have multiple scenes with many answers and dialogue decisions and I can’t really think of a better way of catching all the errors than doing it globally. I tried doing this:

But it doesn’t seem to work properly, there is a certain type of request/response that I can’t catch. This is the error for it:

/node_modules/telegraf/lib/composer.js:471:17) at async /

/node_modules/telegraf/lib/composer.js:472:21 at async execute (/

/node_modules/telegraf/lib/composer.js:471:17) at async /

/node_modules/telegraf/lib/composer.js:472:21 at async execute (/

/node_modules/telegraf/lib/composer.js:471:17) at async execute (/

/node_modules/telegraf/lib/composer.js:471:17) at async /

All the other errors are caught just fine. Also I dont know where old_chat_member and new_chat_member comes from — bot can’t be used in the groups so it shouldn’t appear.

Источник

Originally posted by kapisolec December 6, 2022
Hello, I would like to ask is there a way to globally catch all the errors regarding requests/responses that Telegram sends? I have multiple scenes with many answers and dialogue decisions and I can’t really think of a better way of catching all the errors than doing it globally. I tried doing this:

process.on("uncaughtException", (err) => {
  console.log(err);
});

process.on("unhandledRejection", (err) => {
  console.log(err);
});

bot.catch((err, ctx) => {
  console.log(err, ctx);
});

But it doesn’t seem to work properly, there is a certain type of request/response that I can’t catch. This is the error for it:

Unhandled error while processing {
  update_id: <id>,
  my_chat_member: {
    chat: {
      id: <id>,
      first_name: '<name>',
      username: '<name>',
      type: 'private'
    },
    from: {
      id: <id>,
      is_bot: false,
      first_name: '<name>',
      username: '<name>',
      language_code: 'en'
    },
    date: 1670331646,
    old_chat_member: { user: [Object], status: 'member' },
    new_chat_member: { user: [Object], status: 'kicked', until_date: 0 }
  }
}
TelegramError: 403: Forbidden: bot was blocked by the user
    at Telegram.callApi (/<path>/node_modules/telegraf/lib/core/network/client.js:291:19)
    at runMicrotasks (<anonymous>)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async execute (/<path>/node_modules/telegraf/lib/composer.js:471:17)
    at async /<path>/node_modules/telegraf/lib/composer.js:472:21
    at async execute (/<path>/node_modules/telegraf/lib/composer.js:471:17)
    at async /<path>/node_modules/telegraf/lib/composer.js:472:21
    at async execute (/<path>/node_modules/telegraf/lib/composer.js:471:17)
    at async execute (/<path>/node_modules/telegraf/lib/composer.js:471:17)
    at async /<path>/node_modules/telegraf/lib/composer.js:472:21 {
  response: {
    ok: false,
    error_code: 403,
    description: 'Forbidden: bot was blocked by the user'
  },
  on: {
    method: 'sendMessage',
    payload: { chat_id: <id>, text: 'Choose an option' }
  }
}

All the other errors are caught just fine. Also I dont know where old_chat_member and new_chat_member comes from — bot can’t be used in the groups so it shouldn’t appear.

Context

  • Telegraf.js Version: 4.11.2
  • Node.js Version: 16.13.0
  • Operating System: Windows

Minimal Example Code Reproducing the Issue

bot.command("translate", (ctx) => {
  // type in any text the bot will detect the language and translate to your target language
  const outerContext = ctx;
  ctx.reply("Type in any text to translate");

  // get the text from the user
  bot.on("text", async (ctx) => {
    const text = ctx.message.text;
    // get the language code by awaiting on the detect function
    const language = await api.detect(text);
    console.log(language);
    const detectedLanguage = Object.keys(languageCodeMapping).find(
      (key) => languageCodeMapping[key] === language
    );

    ctx.reply(`The detected language is ${detectedLanguage}`);
    ctx.reply("Choose the target language", {
      reply_markup: {
        keyboard: [
          ["english", "chinese", "french", "german", "italian"],
          ["japanese", "korean", "portuguese", "russian", "spanish"],
          ["amharic", "hindi", "arabic", "turkish", "greek"],
        ],
        one_time_keyboard: true,
      },
    });    
    bot.on("text", async (ctx) => {
      const targetLanguage = ctx.message.text;
      const translated = await api.translate(
        language,
        languageCodeMapping[targetLanguage],
        text
      );
      ctx.reply(`${translated}`);
    });
  });
});

Expected Behavior

This was supposed to move on to the next prompt after the user entering the target language

Current Behavior

Stuck inside a loop prompting the user again and again for the target language

Additional

When I looked at the internal implementation of bot.on() it has I think a conflicting namespace.

`
on<Filter extends tt.UpdateType | Guard<C[‘update’]>>(
filters: MaybeArray,
…fns: NonemptyReadonlyArray<Middleware<FilteredContext<C, Filter>>>
): this

  • Registers middleware for handling updates narrowed by update types or message subtypes.
  • @deprecated Use filter utils instead. Support for Message subtype in Composer::on will be removed in Telegraf v5.

on<Filter extends tt.UpdateType | tt.MessageSubType>(
filters: MaybeArray,
…fns: NonemptyReadonlyArray<
Middleware<NarrowedContext<C, tt.MountMap[Filter]>>
>
): this

on<Filter extends tt.UpdateType | tt.MessageSubType | Guard<C[‘update’]>>(
filters: MaybeArray,
…fns: NonemptyReadonlyArray<
Middleware<
Filter extends tt.MessageSubType
? MatchedContext<C, Filter>
: Filter extends tt.UpdateType | Guard<C[‘update’]>
? FilteredContext<C, Filter>
: never
>
>
): this {
// @ts-expect-error This should get resolved when the overloads are removed in v5
return this.use(Composer.on(filters, …fns))
}
`

In my scenario it is using the deprecated version of it!

06.05.2022, 14:14. Показов 1018. Ответов 0


Делаю по уроку сцены через телеграф и получил следующую ошибку:

Код

C:UsersUsernameWebstormProjectsuntitled1node_modulestelegraflibscenesstage.js:17
                throw new Error('telegraf: Unsupported scene');
                ^

Error: telegraf: Unsupported scene
    at C:UsersUsernameWebstormProjectsuntitled1node_modulestelegraflibscenesstage.js:17:23
    at Array.forEach (<anonymous>)
    at Stage.register (C:UsersUsernameWebstormProjectsuntitled1node_modulestelegraflibscenesstage.js:15:16)
    at C:UsersUsernameWebstormProjectsuntitled1node_modulestelegraflibscenesstage.js:12:40
    at Array.forEach (<anonymous>)
    at new Stage (C:UsersUsernameWebstormProjectsuntitled1node_modulestelegraflibscenesstage.js:12:16)     
    at Object.<anonymous> (C:UsersUsernameWebstormProjectsuntitled1index.js:8:15)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)

Код index.js
Добавлено через 2 минуты

Javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const { Scenes, session, Telegraf} = require('telegraf')
//const config = require('config')
 
const bot = new Telegraf('token')
const SceneGenerator=require('./scenes')
const currScene = new SceneGenerator()
const appScene = currScene.GenAppScene()
const stage = new Scenes.Stage([appScene])
bot.use(session())
bot.use(stage.middleware())
bot.command('HI',async (ctx)=>{
    await ctx.scene.enter('app')
})
 
bot.start((ctx) => ctx.reply('Welcome'))
bot.help((ctx) => ctx.reply('Send me a sticker'))
bot.on('sticker', (ctx) => ctx.reply('������'))
bot.hears('hi', (ctx) => ctx.reply('Hey there'))
 
bot.launch()

Код scenes.js

Javascript
1
2
3
4
5
6
7
8
9
10
11
const {Scenes} = require('telegraf')
 
class SceneGenerator{
    GenAppScene (){
        const app = new Scenes.BaseScene('GenAppScene')
        app.enter(async (ctx)=>{
            await  ctx.reply('Привет это код на Telegraf')
            await ctx.scene.leave()
        })
    }}
module.exports=SceneGenerator

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

I tried to make a scene for telegraf js telegrams, but I’m making a mistake. I couldn’t find a solution to the problem.

Error: telegraf: Unsupported scene
    at D:ProjectsbotsBuyBooksnode_modulestelegrafstage.js:19:15
    at Array.forEach (<anonymous>)
    at Stage.register (D:ProjectsbotsBuyBooksnode_modulestelegrafstage.js:17:12)
    at D:ProjectsbotsBuyBooksnode_modulestelegrafstage.js:13:36
    at Array.forEach (<anonymous>)
    at new Stage (D:ProjectsbotsBuyBooksnode_modulestelegrafstage.js:13:12)
    at Object.<anonymous> (D:ProjectsbotsBuyBookstelegrambot.js:11:15)
    at Module._compile (internal/modules/cjs/loader.js:1133:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)

Here’s the key file code:

const { Telegraf} = require('telegraf'),
config             = require("./config/config.json"),
{Extra,Markup,Stage ,session} = Telegraf,
bot                = new Telegraf(config.token),
SceneGenerator     = require('./scenes'),
curScene           = new SceneGenerator,
SearchSchene       = curScene.GenSearchSchene,
InfoSchene         = curScene.GenInfoSchene,
BookTopSchene      = curScene.GenBookTopSchene;

const stage = new Stage([SearchSchene, InfoSchene, BookTopSchene])

bot.use(session())
bot.use(stage.middleware())

bot.start((ctx) => ctx.reply('Привет ! Напиши /help чтобы получить больше информации'))
bot.help((ctx) => ctx.reply('Список моих команд:n|1. /search - поиск книги|n|2. /info - краткая информация о книге|n|3. /bookTop - топ книг с различных сайтов|'))
bot.command('search', async (ctx) => {
await ctx.scene.enter('search')
})
bot.launch()

Here’s the stage code:

const Scene = require("telegraf/scenes/base")

class SceneGenerator {
GenSearchSchene(){
const search = new Scene('search')
search.enter(async (ctx) =>{
await ctx.reply('Для поиска введите название книги')
})
search.on('text', async (ctx) =>{
const name = ctx.message.text
//проверяем наличие текста
if(name){
await ctx.reply('Идёт обработка . Это может занять некоторое время...')
await ctx.scene.leave();
}else{
await ctx.reply("Мне непонятно данное имя")
await ctx.scene.reenter()
}
})
search.on('message', (ctx) =>{
ctx.reply('Ты меня за дибила считаешь ?')
})
return search;

}
GenInfoSchene(){
    const info = new Scene('info')
    info.enter(async (ctx) =&gt;{
        await ctx.reply('Для поиска информации введите название книги')
    })
    info.on('text', async (ctx) =&gt;{
        const name = ctx.message.text
        //проверяем наличие текста
        if(name){
            await ctx.reply('Идёт обработка . Это может занять некоторое время...')
            ctx.scene.leave()
        }else{
            await ctx.reply("Мне непонятно данное имя")
            await ctx.scene.reenter()
        }
    })
    info.on('message', (ctx) =&gt;{
        ctx.reply('Ты меня за дибила считаешь ?')
    })
    return info
}
GenBookTopSchene(){
    const bookTop = new Scene('bookTop')
    bookTop.enter(async (ctx) =&gt;{
        await ctx.reply('Введите колличество книг которое хотите получить')
    })
    bookTop.on('text', async (ctx) =&gt;{
        const currAge = Number(ctx.message.text)
        if(currAge &amp;&amp; currAge &gt; 0){
            await ctx.reply('Идёт обработка . Это может занять некоторое время...')
            await ctx.scene.leave()
        }else{
            await ctx.reply("Вы ввели не число или число равное/меньше нуля")
            await ctx.scene.reenter()
        }

    })
    bookTop.on('message', (ctx) =&gt;{
        ctx.reply('Ты меня за дибила считаешь ?')
    })
    return bookTop
}

}
module.exports = SceneGenerator

[SOLVED] — missing input plugin

I’m want to run an Ubuntu LXC container in Proxmox for InfluxDB, telegraf, chronograf, and Grafana. I have InfluxDB installed and running, but I’m having trouble getting telegraf to run. Telegraf keeps failing with this error: «Failed to start The plugin-driven server agent for reporting metrics into InfluxDB.»

I see other people reporting this issue, but not really any solutions. I’ve installed the TICK stack on other systems (raspberry pi’s, ubuntu VM) before without problems. Is a container install of Telegraf likely to cause this issue?

Sep 11 20:33:21 CT-104-tick telegraf[16886]: 2020-09-11T20:33:21Z I! Starting Telegraf 1.14.5

Sep 11 20:33:21 CT-104-tick telegraf[16886]: 2020-09-11T20:33:21Z E! [telegraf] Error running agent: Error: no inputs found, did you provide a valid config file

Sep 11 20:33:21 CT-104-tick systemd[1]: telegraf.service: Main process exited, code=exited, status=1/FAILURE

Sep 11 20:33:21 CT-104-tick systemd[1]: telegraf.service: Failed with result ‘exit-code’.

Sep 11 20:33:21 CT-104-tick systemd[1]: telegraf.service: Service hold-off time over, scheduling restart.

Sep 11 20:33:21 CT-104-tick systemd[1]: telegraf.service: Scheduled restart job, restart counter is at 5.

Sep 11 20:33:21 CT-104-tick systemd[1]: Stopped The plugin-driven server agent for reporting metrics into InfluxDB.

Sep 11 20:33:21 CT-104-tick systemd[1]: telegraf.service: Start request repeated too quickly.

Sep 11 20:33:21 CT-104-tick systemd[1]: telegraf.service: Failed with result ‘exit-code’.

Sep 11 20:33:21 CT-104-tick systemd[1]: Failed to start The plugin-driven server agent for reporting metrics into InfluxDB.

My telegraf.conf is pretty simple:

# Global Agent Configuration

[agent]

hostname = "hakase-tig"

flush_interval = "15s"

interval = "15s"

# Input Plugins

# Output Plugin InfluxDB

[[outputs.influxdb]]

database = "telegraf"

urls = ["http://127.0.0.1:8086"]

username = "telegrafusr"

password = "xxxxx"

timeout = "37s"

And I think I have the right correct database, user, and password:

Connected to http://localhost:8086 version 1.8.0

InfluxDB shell version: 1.8.0

> use telegraf

Using database telegraf

> show users

user admin

---- -----

telegrafusr false

Понравилась статья? Поделить с друзьями:
  • Undertale soul ops error sans
  • Undertale judgement day wiki fatal error
  • Undertale judgement day error 404 jacket
  • Undertale heroes of determination error sans
  • Undertale fight for love fatal error sans