Skip to content

Commit

Permalink
Normalize strings with black
Browse files Browse the repository at this point in the history
Signed-off-by: alfred richardsn <rchrdsn@protonmail.ch>
  • Loading branch information
r4rdsn committed Nov 12, 2019
1 parent 911d069 commit 74ddb6f
Show file tree
Hide file tree
Showing 21 changed files with 820 additions and 822 deletions.
22 changes: 11 additions & 11 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,43 @@
import os
import sys

sys.path.insert(0, os.path.abspath('../'))
sys.path.insert(0, os.path.abspath("../"))


# -- Project information -----------------------------------------------------

project = 'TellerBot'
copyright = '2019, alfred richardsn'
author = 'alfred richardsn'
project = "TellerBot"
copyright = "2019, alfred richardsn"
author = "alfred richardsn"


# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc']
extensions = ["sphinx.ext.autodoc"]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]


# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]

master_doc = 'index'
autodoc_mock_imports = ['src.config']
master_doc = "index"
autodoc_mock_imports = ["src.config"]
2 changes: 0 additions & 2 deletions pyproject.toml

This file was deleted.

6 changes: 3 additions & 3 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ async def on_startup(webhook_path, *args):
Set webhook and run background tasks.
"""
await tg.delete_webhook()
await tg.set_webhook('https://' + config.SERVER_HOST + webhook_path)
await tg.set_webhook("https://" + config.SERVER_HOST + webhook_path)
asyncio.create_task(notifications.run_loop())
asyncio.create_task(connect_to_blockchains())

Expand All @@ -43,13 +43,13 @@ def main():
Bot's main entry point.
"""
url_token = secrets.token_urlsafe()
webhook_path = config.WEBHOOK_PATH + '/' + url_token
webhook_path = config.WEBHOOK_PATH + "/" + url_token

executor.start_webhook(
dispatcher=dp,
webhook_path=webhook_path,
on_startup=lambda *args: on_startup(webhook_path, *args),
host='127.0.0.1',
host="127.0.0.1",
port=config.SERVER_PORT,
)
print() # Executor stopped with ^C
Expand Down
4 changes: 2 additions & 2 deletions src/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@
dp.middleware.setup(i18n)

logging.basicConfig(
filename=config.LOG_FILENAME, filemode='a', level=config.LOGGER_LEVEL
filename=config.LOG_FILENAME, filemode="a", level=config.LOGGER_LEVEL
)
dp.middleware.setup(LoggingMiddleware())
else:
tg = Bot('', validate_token=False)
tg = Bot("", validate_token=False)
dp = Dispatcher(tg)


Expand Down
10 changes: 5 additions & 5 deletions src/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,27 +23,27 @@


client = AsyncIOMotorClient()
database = client[DATABASE_NAME if isinstance(DATABASE_NAME, str) else 'tellerbot']
database = client[DATABASE_NAME if isinstance(DATABASE_NAME, str) else "tellerbot"]

STATE_KEY = 'state'
STATE_KEY = "state"


class MongoStorage(BaseStorage):
"""MongoDB asynchronous storage for FSM using motor."""

async def get_state(self, user: int, **kwargs) -> typing.Optional[str]:
"""Get current state of user with Telegram ID ``user``."""
document = await database.users.find_one({'id': user})
document = await database.users.find_one({"id": user})
return document.get(STATE_KEY) if document else None

async def set_state(
self, user: int, state: typing.Optional[str] = None, **kwargs
) -> None:
"""Set new state ``state`` of user with Telegram ID ``user``."""
if state is None:
await database.users.update_one({'id': user}, {'$unset': {STATE_KEY: True}})
await database.users.update_one({"id": user}, {"$unset": {STATE_KEY: True}})
else:
await database.users.update_one({'id': user}, {'$set': {STATE_KEY: state}})
await database.users.update_one({"id": user}, {"$set": {STATE_KEY: state}})

async def finish(self, user, **kwargs):
"""Finish conversation with user."""
Expand Down
2 changes: 1 addition & 1 deletion src/escrow/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@


SUPPORTED_BLOCKCHAINS = (GolosBlockchain(),)
SUPPORTED_BANKS = ('Alfa-Bank', 'Rocketbank', 'Sberbank', 'Tinkoff')
SUPPORTED_BANKS = ("Alfa-Bank", "Rocketbank", "Sberbank", "Tinkoff")


def get_escrow_instance(asset: str):
Expand Down
102 changes: 51 additions & 51 deletions src/escrow/blockchain/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class BaseBlockchain(ABC):
address: str
#: Template of URL to transaction in blockchain explorer. Should
#: contain ``{}`` which gets replaced with transaction id.
explorer: str = '{}'
explorer: str = "{}"

_queue: typing.List[typing.Mapping[str, typing.Any]] = []

Expand Down Expand Up @@ -114,12 +114,12 @@ async def check_transaction(
"""Add transaction in ``self._queue`` to be checked."""
self._queue.append(
{
'offer_id': offer_id,
'from_address': from_address,
'amount_with_fee': amount_with_fee,
'amount_without_fee': amount_without_fee,
'asset': asset,
'memo': memo,
"offer_id": offer_id,
"from_address": from_address,
"amount_with_fee": amount_with_fee,
"amount_without_fee": amount_without_fee,
"asset": asset,
"memo": memo,
}
)
# Start streaming if not already streaming
Expand All @@ -133,7 +133,7 @@ def remove_from_queue(self, offer_id: ObjectId) -> bool:
:return: True if transaction was found and False otherwise.
"""
for queue_member in self._queue:
if queue_member['offer_id'] == offer_id:
if queue_member["offer_id"] == offer_id:
self._queue.remove(queue_member)
return True
return False
Expand All @@ -157,63 +157,63 @@ async def _confirmation_callback(
:param block_num: Number of block to confirm.
:return: True if transaction was confirmed and False otherwise.
"""
offer = await database.escrow.find_one({'_id': offer_id})
offer = await database.escrow.find_one({"_id": offer_id})
if not offer:
return False

if offer['type'] == 'buy':
new_currency = 'sell'
escrow_user = offer['init']
other_user = offer['counter']
elif offer['type'] == 'sell':
new_currency = 'buy'
escrow_user = offer['counter']
other_user = offer['init']
if offer["type"] == "buy":
new_currency = "sell"
escrow_user = offer["init"]
other_user = offer["counter"]
elif offer["type"] == "sell":
new_currency = "buy"
escrow_user = offer["counter"]
other_user = offer["init"]

answer = _(
"Transaction has passed. I'll notify should you get {}.",
locale=escrow_user['locale'],
locale=escrow_user["locale"],
)
answer = answer.format(offer[new_currency])
await tg.send_message(escrow_user['id'], answer)
await tg.send_message(escrow_user["id"], answer)
is_confirmed = await create_task(self.is_block_confirmed(block_num, op))
if is_confirmed:
await database.escrow.update_one(
{'_id': offer['_id']}, {'$set': {'trx_id': trx_id}}
{"_id": offer["_id"]}, {"$set": {"trx_id": trx_id}}
)
keyboard = InlineKeyboardMarkup()
keyboard.add(
InlineKeyboardButton(
_('Sent', locale=other_user['locale']),
callback_data='tokens_sent {}'.format(offer['_id']),
_("Sent", locale=other_user["locale"]),
callback_data="tokens_sent {}".format(offer["_id"]),
)
)
answer = markdown.link(
_('Transaction is confirmed.', locale=other_user['locale']),
_("Transaction is confirmed.", locale=other_user["locale"]),
self.trx_url(trx_id),
)
answer += '\n' + markdown.escape_md(
_('Send {} {} to address {}', locale=other_user['locale']).format(
offer[f'sum_{new_currency}'],
answer += "\n" + markdown.escape_md(
_("Send {} {} to address {}", locale=other_user["locale"]).format(
offer[f"sum_{new_currency}"],
offer[new_currency],
escrow_user['receive_address'],
escrow_user["receive_address"],
)
)
answer += '.'
answer += "."
await tg.send_message(
other_user['id'],
other_user["id"],
answer,
reply_markup=keyboard,
parse_mode=ParseMode.MARKDOWN,
)
return True

await database.escrow.update_one(
{'_id': offer['_id']}, {'$set': {'transaction_time': time()}}
{"_id": offer["_id"]}, {"$set": {"transaction_time": time()}}
)
answer = _('Transaction is not confirmed.', locale=escrow_user['locale'])
answer += ' ' + _('Please try again.', locale=escrow_user['locale'])
await tg.send_message(escrow_user['id'], answer)
answer = _("Transaction is not confirmed.", locale=escrow_user["locale"])
answer += " " + _("Please try again.", locale=escrow_user["locale"])
await tg.send_message(escrow_user["id"], answer)
return False

async def _refund_callback(
Expand All @@ -236,42 +236,42 @@ async def _refund_callback(
:param amount: Amount of transferred asset.
:param asset: Transferred asset.
"""
offer = await database.escrow.find_one({'_id': offer_id})
offer = await database.escrow.find_one({"_id": offer_id})
if not offer:
return

user = offer['init'] if offer['type'] == 'buy' else offer['counter']
answer = _('There are mistakes in your transfer:', locale=user['locale'])
user = offer["init"] if offer["type"] == "buy" else offer["counter"]
answer = _("There are mistakes in your transfer:", locale=user["locale"])

for reason in reasons:
if reason == 'asset':
point = _('wrong asset', locale=user['locale'])
elif reason == 'amount':
point = _('wrong amount', locale=user['locale'])
elif reason == 'memo':
point = _('wrong memo', locale=user['locale'])
if reason == "asset":
point = _("wrong asset", locale=user["locale"])
elif reason == "amount":
point = _("wrong amount", locale=user["locale"])
elif reason == "memo":
point = _("wrong memo", locale=user["locale"])
else:
continue
answer += '\n' + point
answer += "\n" + point

answer += '\n\n' + _(
'Transaction will be refunded after confirmation.', locale=user['locale']
answer += "\n\n" + _(
"Transaction will be refunded after confirmation.", locale=user["locale"]
)
await tg.send_message(user['id'], answer, parse_mode=ParseMode.MARKDOWN)
await tg.send_message(user["id"], answer, parse_mode=ParseMode.MARKDOWN)
is_confirmed = await create_task(self.is_block_confirmed(block_num, op))
await database.escrow.update_one(
{'_id': offer['_id']}, {'$set': {'transaction_time': time()}}
{"_id": offer["_id"]}, {"$set": {"transaction_time": time()}}
)
if is_confirmed:
trx_id = await self.transfer(from_address, amount, asset)
answer = markdown.link(
_('Transaction is refunded.', locale=user['locale']),
_("Transaction is refunded.", locale=user["locale"]),
self.trx_url(trx_id),
)
else:
answer = _('Transaction is not confirmed.', locale=user['locale'])
answer += ' ' + _('Please try again.', locale=user['locale'])
await tg.send_message(user['id'], answer, parse_mode=ParseMode.MARKDOWN)
answer = _("Transaction is not confirmed.", locale=user["locale"])
answer += " " + _("Please try again.", locale=user["locale"])
await tg.send_message(user["id"], answer, parse_mode=ParseMode.MARKDOWN)


class BlockchainConnectionError(Exception):
Expand Down

0 comments on commit 74ddb6f

Please sign in to comment.