Home > Net >  Plot a function with telegram bot (python, matplotlib)
Plot a function with telegram bot (python, matplotlib)

Time:11-25

I faced with the problem during telegram bot writing. I would be very happy if somebody help me with this.

My code

import telebot 
import matplotlib.pyplot as plt
import numpy as np

...
def plot_func(message):
    x = np.linspace(-5,5,100)
    y = message.text # <-- here is something wrong I supppose

    plt.plot(x, y, 'r')
    plt.savefig('plot_name.png', dpi = 300)
    bot.send_photo(message.chat.id, photo=open('plot_name.png', 'rb'))
    #plt.show()

Main idea

User send function, bot plot it and send image back:enter image description here

ERROR

/home/anmnv/Desktop/news_scrapper_bot/bot.py:148: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
  plt.plot(x, y, 'r')
Traceback (most recent call last):
  File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 424, in <module>
    bot.polling(none_stop=True)
  File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1047, in polling
    self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
  File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1122, in __threaded_polling
    raise e
  File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1078, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 154, in raise_exceptions
    raise self.exception_info
  File "/home/anmnv/.local/lib/python3.10/site-packages/telebot/util.py", line 98, in run
    task(*args, **kwargs)
  File "/home/anmnv/Desktop/news_scrapper_bot/bot.py", line 148, in plot_func
    plt.plot(x, y, 'r')
  File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/pyplot.py", line 2730, in plot
    return gca().plot(
  File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_axes.py", line 1662, in plot
    lines = [*self._get_lines(*args, data=data, **kwargs)]
  File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 311, in __call__
    yield from self._plot_args(
  File "/home/anmnv/.local/lib/python3.10/site-packages/matplotlib/axes/_base.py", line 504, in _plot_args
    raise ValueError(f"x and y must have same first dimension, but "
ValueError: x and y must have same first dimension, but have shapes (100,) and (1,)

Thank you in advance

CodePudding user response:

Assuming message.text contains the string 'x**2', you can use enter image description here

  • Related