我的代码出错了,我不知道哪里出了问题
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()
我发现该错误似乎来自一个用户。也就是说,一个注册了,给了他一个代码,第二个刚刚注册,由于错误没有给出代码。