1
Fork 0
mirror of https://github.com/Steffo99/greed.git synced 2024-11-24 06:44:19 +00:00

Reformat code using PyCharm

This commit is contained in:
Steffo 2020-09-07 17:13:27 +02:00
parent b49bc0d94d
commit 9d80c4c5fb
12 changed files with 173 additions and 157 deletions

19
core.py
View file

@ -1,16 +1,18 @@
import logging
import os import os
import sys import sys
import telegram
import worker
import nuconfig
import threading import threading
import localization
import logging
import duckbot
import sqlalchemy import sqlalchemy
import sqlalchemy.orm
import sqlalchemy.ext.declarative as sed import sqlalchemy.ext.declarative as sed
import sqlalchemy.orm
import telegram
import database import database
import duckbot
import localization
import nuconfig
import worker
try: try:
import coloredlogs import coloredlogs
@ -173,7 +175,8 @@ def main():
receiving_worker = chat_workers.get(update.callback_query.from_user.id) receiving_worker = chat_workers.get(update.callback_query.from_user.id)
# Ensure a worker exists for the chat # Ensure a worker exists for the chat
if receiving_worker is None: if receiving_worker is None:
log.debug(f"Received a callback query in a chat without worker: {update.callback_query.from_user.id}") log.debug(
f"Received a callback query in a chat without worker: {update.callback_query.from_user.id}")
# Suggest that the user restarts the chat with /start # Suggest that the user restarts the chat with /start
bot.send_message(update.callback_query.from_user.id, default_loc.get("error_no_worker_for_chat")) bot.send_message(update.callback_query.from_user.id, default_loc.get("error_no_worker_for_chat"))
# Skip the update # Skip the update

View file

@ -1,22 +1,24 @@
import typing
from sqlalchemy import create_engine, Column, ForeignKey, UniqueConstraint
from sqlalchemy import Integer, BigInteger, String, Text, LargeBinary, DateTime, Boolean
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
import telegram
import requests
import utils
import logging import logging
import typing
import requests
import telegram
from sqlalchemy import Column, ForeignKey, UniqueConstraint
from sqlalchemy import Integer, BigInteger, String, Text, LargeBinary, DateTime, Boolean
from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
from sqlalchemy.orm import relationship, backref
import utils
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
import worker import worker
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
# Create a base class to define all the database subclasses # Create a base class to define all the database subclasses
TableDeclarativeBase = declarative_base() TableDeclarativeBase = declarative_base()
# Define all the database tables using the sqlalchemy declarative base # Define all the database tables using the sqlalchemy declarative base
class User(DeferredReflection, TableDeclarativeBase): class User(DeferredReflection, TableDeclarativeBase):
"""A Telegram user who used the bot at least once.""" """A Telegram user who used the bot at least once."""

View file

@ -1,9 +1,11 @@
import nuconfig
import telegram.error
import logging import logging
import sys
import time import time
import traceback import traceback
import sys
import telegram.error
import nuconfig
log = logging.getLogger(__name__) log = logging.getLogger(__name__)

View file

@ -1,15 +1,15 @@
from typing import *
import importlib import importlib
import types
import logging
import json import json
import logging
import types
from typing import *
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class IgnoreDict(dict): class IgnoreDict(dict):
"""A dictionary that if passed to format_map, ignores the missing replacement fields.""" """A dictionary that if passed to format_map, ignores the missing replacement fields."""
def __missing__(self, key): def __missing__(self, key):
return "{" + key + "}" return "{" + key + "}"

View file

@ -1,7 +1,7 @@
from typing import *
import toml
import logging import logging
from typing import *
import toml
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
CompareReport = Dict[str, Union[str, List[str], "Missing"]] CompareReport = Dict[str, Union[str, List[str], "Missing"]]

View file

@ -104,7 +104,7 @@ conversation_live_orders_start = "Вы в режиме <b>Новые заказ
"Все новые заказы появятся в этом чате в режиме реального времени," \ "Все новые заказы появятся в этом чате в режиме реального времени," \
" и их можно отметить ✅ Выполнено" \ " и их можно отметить ✅ Выполнено" \
" или ✴️ Возвращено в случае возврата денег." \ " или ✴️ Возвращено в случае возврата денег." \
\
# Live orders mode: stop receiving messages # Live orders mode: stop receiving messages
conversation_live_orders_stop = "<i>Нажмите Стоп в этом чате, чтобы остановить этот режим.</i>" conversation_live_orders_stop = "<i>Нажмите Стоп в этом чате, чтобы остановить этот режим.</i>"

View file

@ -52,7 +52,7 @@ transactions_page = "Page <b>{page}</b>:\n" \
# transactions.csv caption # transactions.csv caption
csv_caption = "生成了一个📄.csv文件,其中包含bot的数据库中多所有事物\n" \ csv_caption = "生成了一个📄.csv文件,其中包含bot的数据库中多所有事物\n" \
"您可以使用其他程序(例如LibreOffice Calc)打开此文件并进行处理数据" \ "您可以使用其他程序(例如LibreOffice Calc)打开此文件并进行处理数据" \
\
# Conversation: the start command was sent and the bot should welcome the user # Conversation: the start command was sent and the bot should welcome the user
conversation_after_start = "您好!\n" \ conversation_after_start = "您好!\n" \
"欢迎使用greed系统!\n" \ "欢迎使用greed系统!\n" \

View file

@ -1,26 +1,29 @@
import threading
from typing import *
import uuid
import datetime import datetime
import telegram
import nuconfig
import sys
import queue as queuem
import database as db
import re
import os
import traceback
from html import escape
import requests
import logging import logging
import localization import os
import queue as queuem
import re
import sys
import threading
import traceback
import uuid
from html import escape
from typing import *
import requests
import sqlalchemy.orm import sqlalchemy.orm
import telegram
import database as db
import localization
import nuconfig
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
class StopSignal: class StopSignal:
"""A data class that should be sent to the worker when the conversation has to be stopped abnormally.""" """A data class that should be sent to the worker when the conversation has to be stopped abnormally."""
def __init__(self, reason: str = ""): def __init__(self, reason: str = ""):
self.reason = reason self.reason = reason
@ -759,7 +762,8 @@ class Worker(threading.Thread):
self.bot.send_message(self.chat.id, self.loc.get("conversation_payment_method"), self.bot.send_message(self.chat.id, self.loc.get("conversation_payment_method"),
reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True))
# Wait for a reply from the user # Wait for a reply from the user
selection = self.__wait_for_specific_message([self.loc.get("menu_cash"), self.loc.get("menu_credit_card"), self.loc.get("menu_cancel")], selection = self.__wait_for_specific_message(
[self.loc.get("menu_cash"), self.loc.get("menu_credit_card"), self.loc.get("menu_cancel")],
cancellable=True) cancellable=True)
# If the user has selected the Cash option... # If the user has selected the Cash option...
if selection == self.loc.get("menu_cash"): if selection == self.loc.get("menu_cash"):
@ -790,7 +794,8 @@ class Worker(threading.Thread):
self.bot.send_message(self.chat.id, self.loc.get("payment_cc_amount"), self.bot.send_message(self.chat.id, self.loc.get("payment_cc_amount"),
reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True)) reply_markup=telegram.ReplyKeyboardMarkup(keyboard, one_time_keyboard=True))
# Wait until a valid amount is sent # Wait until a valid amount is sent
selection = self.__wait_for_regex(r"([0-9]+(?:[.,][0-9]+)?|" + self.loc.get("menu_cancel") + r")", cancellable=True) selection = self.__wait_for_regex(r"([0-9]+(?:[.,][0-9]+)?|" + self.loc.get("menu_cancel") + r")",
cancellable=True)
# If the user cancelled the action # If the user cancelled the action
if isinstance(selection, CancelSignal): if isinstance(selection, CancelSignal):
# Exit the loop # Exit the loop
@ -801,11 +806,13 @@ class Worker(threading.Thread):
# Ensure the amount is within the range # Ensure the amount is within the range
if value > self.Price(self.cfg["Payments"]["CreditCard"]["max_amount"]): if value > self.Price(self.cfg["Payments"]["CreditCard"]["max_amount"]):
self.bot.send_message(self.chat.id, self.bot.send_message(self.chat.id,
self.loc.get("error_payment_amount_over_max", max_amount=self.Price(self.cfg["Credit Card"]["max_amount"]))) self.loc.get("error_payment_amount_over_max",
max_amount=self.Price(self.cfg["Credit Card"]["max_amount"])))
continue continue
elif value < self.Price(self.cfg["Payments"]["CreditCard"]["min_amount"]): elif value < self.Price(self.cfg["Payments"]["CreditCard"]["min_amount"]):
self.bot.send_message(self.chat.id, self.bot.send_message(self.chat.id,
self.loc.get("error_payment_amount_under_min", min_amount=self.Price(self.cfg["Credit Card"]["min_amount"]))) self.loc.get("error_payment_amount_under_min",
min_amount=self.Price(self.cfg["Credit Card"]["min_amount"])))
continue continue
break break
# If the user cancelled the action... # If the user cancelled the action...
@ -1162,7 +1169,8 @@ class Worker(threading.Thread):
message_id=update.message.message_id) message_id=update.message.message_id)
# Notify the user of the completition # Notify the user of the completition
self.bot.send_message(order.user_id, self.bot.send_message(order.user_id,
self.loc.get("notification_order_completed", order=order.text(w=self, session=self.session, user=True))) self.loc.get("notification_order_completed",
order=order.text(w=self, session=self.session, user=True)))
# If the user pressed the refund order button, refund the order... # If the user pressed the refund order button, refund the order...
elif update.data == "order_refund": elif update.data == "order_refund":
# Ask for a refund reason # Ask for a refund reason
@ -1302,7 +1310,8 @@ class Worker(threading.Thread):
telegram.InlineKeyboardButton(self.loc.get("menu_next"), callback_data="cmd_next") telegram.InlineKeyboardButton(self.loc.get("menu_next"), callback_data="cmd_next")
) )
# Add a Done button # Add a Done button
inline_keyboard_list.append([telegram.InlineKeyboardButton(self.loc.get("menu_done"), callback_data="cmd_done")]) inline_keyboard_list.append(
[telegram.InlineKeyboardButton(self.loc.get("menu_done"), callback_data="cmd_done")])
# Create the inline keyboard markup # Create the inline keyboard markup
inline_keyboard = telegram.InlineKeyboardMarkup(inline_keyboard_list) inline_keyboard = telegram.InlineKeyboardMarkup(inline_keyboard_list)
# Create the message text # Create the message text