RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / user-696486

Алексей's questions

Martin Hope
Алексей
Asked: 2025-04-16 03:31:47 +0000 UTC

RuntimeError:主线程不在主循环中

  • 5

我的代码出错了,我不知道哪里出了问题

  File "c:\Users\N-2323\Форма регистрации\форма_регистрации.py", line 195, in <module>
    bot.polling(none_stop=True, interval=0)
    ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\__init__.py", line 1198, in polling
    self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                            logger_level=logger_level, allowed_updates=allowed_updates)
                            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\__init__.py", line 1273, in __threaded_polling
    raise e
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\__init__.py", line 1235, in __threaded_polling
    self.worker_pool.raise_exceptions()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\util.py", line 150, in raise_exceptions
    raise self.exception_info
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\telebot\util.py", line 93, in run        
    task(*args, **kwargs)
    ~~~~^^^^^^^^^^^^^^^^^
  File "c:\Users\N-2323\Форма регистрации\форма_регистрации.py", line 185, in org
    img.save('res-cod.png')
    ^^^^^^^^^^^
AttributeError: 'Image' object has no attribute 'savefig'
Exception ignored in atexit callback <bound method Gcf.destroy_all of <class 'matplotlib._pylab_helpers.Gcf'>>:
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\_pylab_helpers.py", line 81, in destroy_all
    manager.destroy()
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\site-packages\matplotlib\backends\_backend_tk.py", line 586, in destroy
    self.canvas._tkcanvas.after_cancel(self.canvas._idle_draw_id)
  File "C:\Users\N-2323\AppData\Local\Programs\Python\Python313\Lib\tkinter\__init__.py", line 894, in after_cancel        
    data = self.tk.call('after', 'info', id)
RuntimeError: main thread is not in main loop

代码(我留了一段,我觉得里面有一些东西):

import os
import requests
from PIL import Image
from io import BytesIO
import matplotlib.pyplot as plt
import telebot
from datetime import datetime
from telebot import types
from telebot.types import InputMediaPhoto
from matplotlib import pyplot as plt
import ssl

bot = telebot.TeleBot('токен');

if not os.path.exists("users.txt"):
    with open("users.txt", "w", encoding="utf-8",  errors='ignore') as f:
        f.write("Дата | Номер кода | ФИО | Телефон | Почта | Номер на мероприятии | Организация\n")

def add_user(data: dict) -> None:
    current_time = datetime.now().strftime("%d.%m.%Y %H:%M")
    record = (
        f"{current_time} | "
        f"{data.get('cod', 'Н/Д')} | "
        f"{data.get('fio', 'Н/Д')} | "
        f"{data.get('phone', 'Н/Д')} | "
        f"{data.get('email', 'Н/Д')} | "
        f"{data.get('org_num', 'Н/Д')} | "
        f"{data.get('org', 'Н/Д')}\n"
    )

    with open("users.txt", "a", encoding="utf-8",  errors='ignore') as f:
        f.write(record)  

def format_data(data: dict) -> str:
    return (
        f"ФИО: {data['fio']}\n"
        f"Телефон: {data['phone']}\n"
        f"Email: {data['email']}\n"
        f"Представитель: {data['org']}"
    )

def generate_barcode(cod):

    url = 'https://barcode.tec-it.com/barcode.ashx'
    params = {
        'data': cod,
        'multiplebarcodes': 'true',
        'translate-esc': 'on'
    }

    response = requests.get(url, params=params, verify=False)

    if response.status_code == 200:
        image = Image.open(BytesIO(response.content))

        return image
    else:
        # Raise an exception if the request failed
        raise Exception(f'Failed to generate barcode. Status code: {response.status_code}')

def main(login: str):
    print(f'Привет, {login}!')  


@bot.message_handler(commands=['start'])
def start(message):
    markup = types.ReplyKeyboardRemove(selective=False)
    bot.send_message(message.chat.id, 'Добро пожаловать! Зарегистрируйтесь на мероприятие.', reply_markup=markup)
    bot.send_message(message.chat.id, "Введите ваше ФИО: ")
    bot.register_next_step_handler(message, fio, data={})

.....

def email(message, data):
    data["email"] = message.text.strip()
    print(data["email"])
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
    btn1 = types.KeyboardButton("1")
    btn2 = types.KeyboardButton("2")
    btn3 = types.KeyboardButton("3")
    markup.add(btn1, btn2, btn3)
    bot.send_message(message.chat.id, '''Выберите, какую роль Вы будете принимать на мероприятии:
1. Фирма экономической игры
2. Участник фестиваля
3. Гости  ''', reply_markup=markup)
    bot.register_next_step_handler(message, org_num, data=data)

def org_num(message, data):
    data["org_num"] = message.text.strip()
    if data["org_num"] == "1":
        print(data["org_num"])
        markup = types.ReplyKeyboardRemove(selective=False)
        Vorg = bot.send_message(message.chat.id, 'Название вашей фирмы: ' , reply_markup=markup)
        bot.register_next_step_handler(message, org, data=data)
    elif data["org_num"] == "3":
        print(data["org_num"])
        markup = types.ReplyKeyboardRemove(selective=False)
        bot.send_message(message.chat.id, 'Напишите "Гость" : ', reply_markup=markup)
        bot.register_next_step_handler(message, org, data=data)
    elif data["org_num"] == "2":
        print(data["org_num"])
        markup = types.ReplyKeyboardRemove(selective=False)
        bot.send_message(message.chat.id, 'Название вашей группы: ', reply_markup=markup)
        bot.register_next_step_handler(message, org, data=data)
    else:
        bot.send_message(message.chat.id, 'Напишите цифру от 1 до 3!')
        bot.send_message(message.chat.id, '''Выберите, какую роль Вы будете принимать на мероприятии:
1. Фирма экономической игры
2. Участник фестиваля
3. Гости ''')
        bot.register_next_step_handler(message, org_num, data=data)

def org(message, data):
    data["org"] = message.text.strip()
    print(data["org"])

    line_count = sum(1 for line in open('users.txt', encoding="utf-8",  errors='ignore'))
    cod_num = 60000 + line_count
    cod_num = str(cod_num)
    cod = '522' + cod_num +'87'
    data["cod"] = cod
    print(data["cod"])

    add_user(data)
    bot.send_message(message.chat.id, "Регистрация прошла успешно!")
    bot.send_message(message.chat.id, f"Ваши данные сохранены:\n{format_data(data)}")

    # Generate the barcode
    barcode_image = generate_barcode(cod)

    # Display the barcode
    plt.imshow(barcode_image)
    plt.savefig('cod.png')
    img = Image.open('cod.png')
    img = img.crop((79, 104, img.width-62, img.height-98))
    img.save('res-cod.png')
    

    file = open('res-cod.png', 'rb')
    bot.send_photo(message.chat.id, file)
    bot.send_message(message.chat.id, '''Сохраните этот штрих-код!

Если хотите зарегистрировать кого-то ещё, напишите /start''')


bot.polling(none_stop=True, interval=0)

if __name__ == '__main__':
    main()

我发现该错误似乎来自一个用户。也就是说,一个注册了,给了他一个代码,第二个刚刚注册,由于错误没有给出代码。

python
  • 1 个回答
  • 50 Views
Martin Hope
Алексей
Asked: 2025-03-24 23:14:25 +0000 UTC

机器人需要将数据输入到文件中。该文件显示 <function fio at 0x>

  • 7

该机器人是为了通过发放条形码来注册活动而创建的。
如何让机器人将变量中的数据输入到文件中,而不是<function fio at 0x> 如何将用户消息从函数写入文件?

代码:

import os
import requests
import telebot
from telebot import types
from telebot.types import

bot = telebot.TeleBot('');


def init_file():  
    if not os.path.exists('users.txt'):
        with open('users.txt', 'w'):
            pass


def add_user(data: str, ifio: str, inumber: str, imail: str, iorg_num: str, iorg: str,) -> bool:
    with open('users.txt', 'r') as f:
        users = f.read().splitlines()  

    with open('users.txt', 'a') as f:
        f.write(f'{data} {ifio} {inumber} {imail} {iorg_num} {iorg}\n')  
    return True

@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, 'Добро пожаловать! Зарегистрируйтесь на мероприятие.')
    Vfio = bot.send_message(message.chat.id, "Ваше ФИО: ")
    bot.register_next_step_handler(Vfio, fio)

def fio(message1):
    ifio = message1.text
    Vnumber = bot.send_message(message1.chat.id, "Ваш номер телефона: ")
    bot.register_next_step_handler(Vnumber, number)
    return ifio

def number(message2):
    inumber = message2.text
    Vmail = bot.send_message(message2.chat.id, "Ваша почта: ")
    bot.register_next_step_handler(Vmail, mail)
    return inumber

def mail(message3):
    imail = message3.text
    Vorg = bot.send_message(message4.chat.id, '''Ваша организация: ''')
    bot.register_next_step_handler(Vorg, org_num)
    return imail

def org(message5):
    iorg = message5.text
    return iorg

    result = add_user(data, ifio, inumber, imail, iorg)  
    bot.send_message(message6.chat.id, 'Регистрация прошла успешно!')
    return

bot.polling(none_stop=True, interval=0)
python
  • 1 个回答
  • 69 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5