old_01
This commit is contained in:
2
doners/telegram-shop-bot-template/.gitattributes
vendored
Normal file
2
doners/telegram-shop-bot-template/.gitattributes
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
# Auto detect text files and perform LF normalization
|
||||
* text=auto
|
||||
152
doners/telegram-shop-bot-template/.gitignore
vendored
Normal file
152
doners/telegram-shop-bot-template/.gitignore
vendored
Normal file
@@ -0,0 +1,152 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
21
doners/telegram-shop-bot-template/LICENSE
Normal file
21
doners/telegram-shop-bot-template/LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 ssayand
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
47
doners/telegram-shop-bot-template/README.md
Normal file
47
doners/telegram-shop-bot-template/README.md
Normal file
@@ -0,0 +1,47 @@
|
||||
i dont like this project tbh :\
|
||||
|
||||
# Telegram shop bot template
|
||||

|
||||

|
||||
[](https://codecov.io/gh/anekobtw/telegram-shop-bot-template)
|
||||

|
||||
|
||||
Customizable telegram shop bot
|
||||
|
||||
## Installing
|
||||
Clone the project to your local machine.
|
||||
```console
|
||||
$ git clone https://github.com/anekobtw/telegram-shop-bot-template.git
|
||||
```
|
||||
|
||||
## Setting up
|
||||
Do not modify any files except `config.py`. Doing so may result in numerous bugs :)
|
||||
|
||||
- Replace `BOT_TOKEN` with your Telegram bot token (Obtain it from [BotFather](https://web.telegram.org/k/#@BotFather)).
|
||||
```python
|
||||
BOT_TOKEN = '' #replace with your token
|
||||
```
|
||||
|
||||
- Change the currency you're using for selling items. (optional)
|
||||
```python
|
||||
currency = '$'
|
||||
```
|
||||
|
||||
- Furthermore, add the products you're selling into the dictionary using the following format:\
|
||||
`'product name' - price`
|
||||
|
||||
```python
|
||||
items = {
|
||||
'Item1': 100,
|
||||
'Item2': 200,
|
||||
'Item3': 500
|
||||
}
|
||||
```
|
||||
|
||||
Remember to restart the bot to apply the changes.
|
||||
|
||||
## Acknowledgements
|
||||
- [aiogram](https://github.com/aiogram/aiogram) - A modern and fully asynchronous framework for Telegram Bot API written in Python using asyncio
|
||||
|
||||
## Contributing
|
||||
Contributions are always welcome! If you have any suggestions, feature requests, or bug reports, please feel free to open an issue on the [GitHub repository](https://github.com/anekobtw/timewise).
|
||||
17
doners/telegram-shop-bot-template/src/config.py
Normal file
17
doners/telegram-shop-bot-template/src/config.py
Normal file
@@ -0,0 +1,17 @@
|
||||
# Insert here your bot token here
|
||||
BOT_TOKEN = ""
|
||||
|
||||
# Enter here the shop owners' telegram ids (@getmyid_bot may help you)
|
||||
# You may add as much as you can, but I recommend not to add too much.
|
||||
admins = {1718021890}
|
||||
|
||||
currency = "$"
|
||||
|
||||
items = {
|
||||
"tissue box": 10,
|
||||
"magnet": 20,
|
||||
"table": 50,
|
||||
"glow stick": 30,
|
||||
"bottle cap": 20,
|
||||
"toothpaste": 15
|
||||
}
|
||||
77
doners/telegram-shop-bot-template/src/database.py
Normal file
77
doners/telegram-shop-bot-template/src/database.py
Normal file
@@ -0,0 +1,77 @@
|
||||
import sqlite3
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class Order:
|
||||
def __init__(self, order_id, tgid, tg_nickname, product, is_open, timestamp) -> None:
|
||||
"""Initialize an order object with provided attributes"""
|
||||
self.order_id = order_id
|
||||
self.tgid = tgid
|
||||
self.tg_nickname = tg_nickname
|
||||
self.product = product
|
||||
self.is_open = is_open
|
||||
self.timestamp = timestamp
|
||||
|
||||
@property
|
||||
def formatted_timestamp(self) -> str:
|
||||
"""Return the timestamp in a formatted string (YYYY-MM-DD HH:MM:SS)"""
|
||||
return datetime.fromtimestamp(self.timestamp).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
def all_data(self) -> str:
|
||||
return f"""Order ID: {self.order_id}
|
||||
Telegram ID: {self.tgid}
|
||||
Telegram Nickname: {self.tg_nickname}
|
||||
Product: {self.product}
|
||||
Date and Time of Purchase: {self.formatted_timestamp}
|
||||
|
||||
"""
|
||||
|
||||
|
||||
class OrderManager:
|
||||
DATABASE_FILE = "database.db"
|
||||
TIMEZONE_OFFSET = 0 # Assuming offset in seconds
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.connection = sqlite3.connect(self.DATABASE_FILE)
|
||||
self.cursor = self.connection.cursor()
|
||||
|
||||
self.cursor.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS orders (
|
||||
order_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
tgid INT,
|
||||
tg_nickname TEXT,
|
||||
product TEXT,
|
||||
is_open INTEGER,
|
||||
timestamp DATETIME
|
||||
)
|
||||
"""
|
||||
)
|
||||
self.connection.commit()
|
||||
|
||||
def get_active_orders(self) -> list:
|
||||
"""Retrieve all orders that are not completed from the database"""
|
||||
self.cursor.execute("SELECT * FROM orders WHERE is_open = 1")
|
||||
return self.cursor.fetchall()
|
||||
|
||||
def get_user_orders(self, tgid: int) -> list:
|
||||
"""Get the information about all user's orders"""
|
||||
self.cursor.execute("SELECT * FROM orders WHERE tgid = ?", (tgid,))
|
||||
return self.cursor.fetchall()
|
||||
|
||||
def get_order(self, order_id: int) -> int:
|
||||
"""Get the order info"""
|
||||
self.cursor.execute("SELECT * FROM orders WHERE order_id = ?", (order_id,))
|
||||
return self.cursor.fetchone()
|
||||
|
||||
def insert_order(self, tgid: int, tg_nickname: str, product: str) -> None:
|
||||
"""Insert a new order into the database with the provided details"""
|
||||
timestamp = round(time.time()) + self.TIMEZONE_OFFSET
|
||||
values = (tgid, tg_nickname, product, 1, timestamp)
|
||||
self.cursor.execute("INSERT INTO orders(tgid, tg_nickname, product, is_open, timestamp) VALUES (?, ?, ?, ?, ?)", values)
|
||||
self.connection.commit()
|
||||
|
||||
def delete_order(self, order_id: int) -> None:
|
||||
"""Delete the order"""
|
||||
self.cursor.execute("DELETE FROM orders WHERE order_id = ?", (order_id,))
|
||||
self.connection.commit()
|
||||
124
doners/telegram-shop-bot-template/src/main.py
Normal file
124
doners/telegram-shop-bot-template/src/main.py
Normal file
@@ -0,0 +1,124 @@
|
||||
import logging
|
||||
|
||||
import config
|
||||
import database
|
||||
from aiogram import Bot, Dispatcher, types
|
||||
from aiogram.types import InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from aiogram.utils import executor
|
||||
from aiogram.utils.callback_data import CallbackData
|
||||
|
||||
# <<< Constants >>>
|
||||
admins = config.admins
|
||||
order_manager = database.OrderManager()
|
||||
order_cb = CallbackData("order", "action", "item")
|
||||
|
||||
|
||||
# <<< Initializing >>>
|
||||
bot = Bot(token=config.BOT_TOKEN)
|
||||
dp = Dispatcher(bot)
|
||||
logging.basicConfig(level=logging.INFO, filename="log.txt")
|
||||
|
||||
|
||||
async def notify_admins_order(order_id: int) -> None:
|
||||
for admin_id in admins:
|
||||
await bot.send_message(chat_id=admin_id, text=f"❗ Check out a new order!\nOrder id: {order_id}\n")
|
||||
|
||||
|
||||
# <<< Inline start buttons >>>
|
||||
@dp.message_handler(commands=["start"])
|
||||
async def start(message: types.Message):
|
||||
keyboard = InlineKeyboardMarkup()
|
||||
keyboard.add(
|
||||
InlineKeyboardButton(text="Check the shop", callback_data="items"),
|
||||
InlineKeyboardButton(text="My orders", callback_data="my_orders"),
|
||||
InlineKeyboardButton(text="Developer", callback_data="developer"),
|
||||
)
|
||||
|
||||
await message.answer(f"Hi!, {message.from_user.mention}!", reply_markup=keyboard)
|
||||
|
||||
|
||||
@dp.callback_query_handler(lambda c: c.data == "items")
|
||||
async def process_callback_items(callback_query: types.CallbackQuery):
|
||||
await callback_query.answer()
|
||||
await items(callback_query.message)
|
||||
|
||||
|
||||
@dp.callback_query_handler(lambda c: c.data == "my_orders")
|
||||
async def process_callback_my_orders(callback_query: types.CallbackQuery):
|
||||
await callback_query.answer()
|
||||
orders_data = order_manager.get_user_orders(callback_query.from_user.id)
|
||||
if orders_data:
|
||||
orders_text = "\n".join(database.Order(*order_data).all_data() for order_data in orders_data)
|
||||
await bot.send_message(chat_id=callback_query.from_user.id, text=orders_text)
|
||||
else:
|
||||
await bot.send_message(chat_id=callback_query.from_user.id, text="You don't have any orders yet.")
|
||||
|
||||
|
||||
@dp.callback_query_handler(lambda c: c.data == "developer")
|
||||
async def process_callback_developer(callback_query: types.CallbackQuery):
|
||||
await bot.send_message(
|
||||
chat_id=callback_query.from_user.id,
|
||||
text="""Bot developer is @anekobtw
|
||||
Telegram channel: @anekobtww
|
||||
Github: https://github.com/anekobtw
|
||||
Source code of this bot: https://github.com/anekobtw/telegram-shop-bot""",
|
||||
)
|
||||
|
||||
|
||||
# <<< Items >>>
|
||||
@dp.message_handler(commands=["items"])
|
||||
async def items(message: types.Message):
|
||||
keyboard = InlineKeyboardMarkup()
|
||||
for item, price in config.items.items():
|
||||
keyboard.add(InlineKeyboardButton(text=f"{item} - {price}{config.currency}", callback_data=order_cb.new(action="create", item=item)))
|
||||
|
||||
await message.answer(text="Choose the product to buy:", reply_markup=keyboard)
|
||||
|
||||
|
||||
@dp.callback_query_handler(order_cb.filter(action="create"))
|
||||
async def order_cb_handler(query: types.CallbackQuery, callback_data: dict):
|
||||
item = callback_data["item"]
|
||||
order_manager.insert_order(query.from_user.id, query.from_user.full_name, item)
|
||||
order_id = database.Order(*order_manager.get_active_orders()[-1]).order_id
|
||||
|
||||
text = f"""You\'ve bought {item} that costs {config.items[item]}{config.currency}
|
||||
Order_id: {order_id}
|
||||
However, if it was an accident, you may delete your purchase by simply typing /delete_order {order_id}"""
|
||||
await bot.send_message(chat_id=query.from_user.id, text=text)
|
||||
await notify_admins_order(order_id=order_id)
|
||||
|
||||
|
||||
# <<< Admin commands >>>
|
||||
@dp.message_handler(commands=["orders"])
|
||||
async def orders(message: types.Message):
|
||||
if message.from_user.id in admins:
|
||||
orders_data = order_manager.get_active_orders()
|
||||
for order_data in orders_data:
|
||||
order_obj = database.Order(*order_data)
|
||||
await message.answer(order_obj.all_data())
|
||||
|
||||
|
||||
@dp.message_handler(commands=["next"])
|
||||
async def next1(message: types.Message):
|
||||
orders_data = order_manager.get_active_orders()
|
||||
order_obj = database.Order(*orders_data[0])
|
||||
await message.answer(order_obj.all_data())
|
||||
|
||||
|
||||
# <<< Others >>>
|
||||
@dp.message_handler(commands=["delete_order"])
|
||||
async def delete_order(message: types.Message):
|
||||
try:
|
||||
args = message.get_args()
|
||||
order_id = int(args.split()[0])
|
||||
except (ValueError, IndexError):
|
||||
await message.answer("The command is used incorrectly. Please, provide me with the order id. Example:\n/delete_order 4 ")
|
||||
else:
|
||||
order_data = order_manager.get_order(order_id)
|
||||
if database.Order(*order_data).tgid == message.from_user.id:
|
||||
order_manager.delete_order(order_id=order_id)
|
||||
await message.answer(f"Order {order_id} was deleted successfully.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
executor.start_polling(dp)
|
||||
1
doners/telegram-shop-bot-template/src/requirements.txt
Normal file
1
doners/telegram-shop-bot-template/src/requirements.txt
Normal file
@@ -0,0 +1 @@
|
||||
aiogram==2.23.1
|
||||
Reference in New Issue
Block a user