Reputation: 1
The program works as it should, that is, it fills in the Google Sheets table, but for some reason, when executing this code, the error This range already has a worksheet with different title set
is displayed. There are no gaps and no (at first glance) problems. I don't understand why. I would keep it, but I want my code to be error-free, even minor ones.
import pygsheets
from datetime import datetime
class GoogleTable:
def __init__(self, credence_service_file: str, googlesheet_file_url: str) -> None:
self.credence_service_file = credence_service_file
self.googlesheet_file_url = googlesheet_file_url
def _get_googlesheet_by_url(self):
try:
client = self._get_googlesheet_client()
sheets = client.open_by_url(self.googlesheet_file_url)
return sheets
except Exception as e:
raise RuntimeError(f"Ошибка подключения к Google Таблице: {e}")
def _get_or_create_sheet(self, sheet_title: str):
sheets = self._get_googlesheet_by_url()
normalized_title = sheet_title.strip()
try:
# Проверяем существующие листы
for sheet in sheets.worksheets():
if sheet.title.strip().lower() == normalized_title.lower():
print(f"Лист найден: {sheet.title}")
return sheet
# Если лист не найден, создаем новый
worksheet = sheets.add_worksheet(normalized_title)
print(f"Создан новый лист: {normalized_title}")
return worksheet
except Exception as e:
raise RuntimeError(f"Ошибка при обработке листа: {e}")
def _get_googlesheet_client(self):
try:
return pygsheets.authorize(service_file=self.credence_service_file)
except Exception as e:
raise RuntimeError(f"Ошибка авторизации Google API: {e}")
def find_admin(self, admin_id: str) -> bool:
worksheet = self._get_or_create_sheet("Админы")
worksheet.refresh()
headers = worksheet.get_row(1)
if "ID" not in headers:
return False
col_index = headers.index("ID") + 1
all_values = worksheet.get_all_values()
for row in all_values[1:]:
if len(row) >= col_index and row[col_index - 1] == admin_id:
return True
return False
def add_admin(self, admin_id: str, full_name: str, username: str, phone_number: str) -> None:
try:
worksheet = self._get_or_create_sheet("Админы")
if self.find_admin(admin_id):
print(f"Админ с ID {admin_id} уже существует.")
return
current_time = datetime.now().strftime("%H:%M %d.%m.%Y")
new_row = [full_name, admin_id, username, phone_number, current_time]
worksheet.append_table(new_row, start="A1", dimension="ROWS", overwrite=False)
print(f"Добавлен новый админ: {full_name}.")
except Exception as e:
print(f"Ошибка добавления админа: {e}")
raise
I tried to solve the problem through ChatGPT. Of course, he offers options, but still such an error comes out. I searched the Internet for options, but in vain
Upvotes: 0
Views: 55