- Saved searches
- Use saved searches to filter your results more quickly
- License
- Modern-Realm/economy-bot-discord.py
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Как сделать экономического бота в Discord на Python?
- Saved searches
- Use saved searches to filter your results more quickly
- License
- AyushSehrawat/eco-bot
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A economy bot — discord; made in python language. Databases used MySQL, SQLite, aiosqlite and mongoDB
License
Modern-Realm/economy-bot-discord.py
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
• In this project you will find different code examples of economy bot with various databases.
• This module makes the process a lot easier !
To create a Discord bot using discord.js, go to economy-bot-discord.js
Thanking JetBrains for Their Support and Assistance
jetbrains.com Once again thank you 💝 for providing me free OSS License.
These IDE(s) made things a lot easier for us:
• WebStorm — The smartest JavaScript IDE
• PyCharm Professional — Python IDE for professional developers
Follow the instructions provided in README.md file in each of the database directories. Like: economy with SQLITE3
$ is the default command prefix
Name | Aliases | Args | Usage |
---|---|---|---|
balance | bal | member | $bal |
deposit | dep | amount | $dep |
withdraw | with | amount | $with |
send | — | member, amount | $send |
leaderboard | lb | None | $lb |
Name | Aliases | Args | Usage |
---|---|---|---|
shop | — | None | $shop |
shop info | — | item_name | $shop |
buy | — | item_name | $buy |
sell | — | item_name | $sell |
inventory | inv | member | $inv |
Name | Aliases | Args | Usage | Cooldown (in days) |
---|---|---|---|---|
daily | — | None | $daily | 1 |
weekly | — | None | $weekly | 7 |
monthly | — | None | $monthly | 30 |
Name | Aliases | Args | Usage |
---|---|---|---|
add_money | addmoney | member, amount, mode | $addmoney |
remove_money | remoney | member, amount, mode | $remoney |
reset_user | — | member | $reset_user |
Note: If your bot is not intended for public use (personal bot) and is only meant to be used on one or two servers that you own, you can add these admin commands. However, if your bot is publicly available for anyone to add to their server, it is not recommended to include these admin commands.
Name | Aliases | Args | Usage |
---|---|---|---|
coin_flip | cf, coinflip | bet_on, amount | $cf |
slots | — | amount | $slots |
dice | — | amount, bet_on | $dice |
New bot commands will be added shortly .
About
A economy bot — discord; made in python language. Databases used MySQL, SQLite, aiosqlite and mongoDB
Как сделать экономического бота в Discord на Python?
Чтобы сделать экономического бота, нужно создать этого бота. Здесь мы не будем об этом писать, но если вы новичок и не знаете, то вот ссылка на статью как это сделать.
После того, как мы добавили его на сервер. То пишем такой код:
import discord from discord.ext import commands from discord.utils import get intents = discord.Intents.all() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) bot.run("[token]")
Вместо «!» можно поставить другой префикс. Это символ, на который будет начинаться любая команда бота. И вместо [token] вставьте туда свой токен своего бота. Запустите бота и проверьте, нет ли ошибок. Если он появился в сети, то значит все работает.
Первое, что можно сделать. Это то, чтобы можно было посмотреть свой баланс, то-есть, посмотреть сколько у вас монет. Для этого, создаем файл wallets.json. В нем будут все данные о нас или о другого участника на сервере. В этот файл нужно только написать <>.
Далее создаем еще один файл stats.py. И пишем туда этот код:
import json WALLET_DEFAULT = async def get_user_wallet(user_id): user_id = str(user_id) with open("wallets.json", "r", encoding="UTF-8") as file: users_wallets = json.load(file) if user_id not in users_wallets.keys(): users_wallets[user_id] = WALLET_DEFAULT with open("wallets.json", "w", encoding="UTF-8") as file: json.dump(users_wallets, file) return users_wallets[user_id] async def set_user_wallet(user_id, parameter, new_value): user_id = str(user_id) with open("wallets.json", "r", encoding="UTF-8") as file: users_wallets = json.load(file) if user_id not in users_wallets.keys(): users_wallets[user_id] = WALLET_DEFAULT users_wallets[user_id][parameter] = new_value with open("wallets.json", "w", encoding="UTF-8") as file: json.dump(users_wallets, file)
Этот код можно просто скопировать. Функция get_user_wallet возвращает нам данные о участнике сервера. Если участника нету в файле wallets.json, то он туда записывается. Функция set_user_wallet изменяет значение его баланса.
Также нужно этот файл импортировать в нашем главном файле. Поэтому пишем этот код в наш первоначальный файл.
import discord from discord.ext import commands from discord.utils import get from stats import * intents = discord.Intents.all() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) bot.run("[token]")
Давайте сделаем первую команду, с помощью которого, можно будет посмотреть свой или баланс другого участника. Данный код копируем и вставляем в первоначальный файл.
import discord from discord.ext import commands from discord.utils import get from stats import * intents = discord.Intents.all() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) @bot.command() async def balance(ctx, user_mention=None): if user_mention is None: user = ctx.author else: user = get(ctx.guild.members, user_wallet = await get_user_wallet(user.id) await ctx.send(f"**Баланс ``: **") bot.run("[token]")
Здесь в функции balance программа проверяет, написали ли мы в user_mention кого-то упоминание. Если да, то находим этого участника по его упоминанию. Если нет, то просто берем за участника того, кто написал команду. Дальше мы по ID участника, получаем его данные. Его баланс и инвентарь. После наш бот пишет в чат что у кого-то есть сколько-то денег. То-есть пишет его баланс.
Теперь мы можем добавить команду, чтобы мы могли задать, добавить или отнять у баланса участника деньги. Для этого пишем этот код в наш главный первоначальный файл.
@bot.command() async def set_money(ctx, user_mention=None, amount=None): if not ctx.author.guild_permissions.administrator: await ctx.send("**У вас нету прав!**") return if user_mention is None or amount is None: await ctx.send("**Заполните все параметры!** `!set_money [user] [amount]`") return user = get(ctx.guild.members, user_wallet = await get_user_wallet(user.id) user_wallet["balance"] = int(amount) await set_user_wallet(user.id, "balance", user_wallet["balance"]) await ctx.send(f"**Баланс `` изменен на !**") @bot.command() async def add_money(ctx, user_mention=None, amount=None): if not ctx.author.guild_permissions.administrator: await ctx.send("**У вас нету прав!**") return if user_mention is None or amount is None: await ctx.send("**Заполните все параметры!** `!add_money [user] [amount]`") return user = get(ctx.guild.members, user_wallet = await get_user_wallet(user.id) user_wallet["balance"] += int(amount) await set_user_wallet(user.id, "balance", user_wallet["balance"]) await ctx.send(f"**К балансу `` прибавлено !**") @bot.command() async def remove_money(ctx, user_mention=None, amount=None): if not ctx.author.guild_permissions.administrator: await ctx.send("**У вас нету прав!**") return if user_mention is None or amount is None: await ctx.send("**Заполните все параметры!** `!remove_money [user] [amount]`") return user = get(ctx.guild.members, user_wallet = await get_user_wallet(user.id) amount = int(amount) if user_wallet["balance"] < amount: await ctx.send(f"**У `` нету столько денег, чтобы их у него убрать!**") return user_wallet["balance"] -= int(amount) await set_user_wallet(user.id, "balance", user_wallet["balance"]) await ctx.send(f"**У баланса `` убрано !**")
Команда set_money задает количество монет в балансе участника сервера. Команда add_money добавляет монеты к балансу, а команда remove_money убирает у баланса монеты. Все эти команды можно использовать, только если у вас есть права Администратора.
Также, давайте сделаем чтобы можно было зарабатывать эти монеты. И зарабатывать их каждую минуту. Для этого мы напишем такую функцию.
@bot.command() @commands.cooldown(1, 60, commands.BucketType.user) # 1, 60 - это сколько раз мы можем использовать эту команду в сколько то времени (1 раз в 60 секунд) async def earn(ctx): user_wallet = await get_user_wallet(ctx.author.id) amount = random.randint(1000, 100000) # Заработок от 1.000 до 100.000 монет в минуту. user_wallet["balance"] += amount await set_user_wallet(ctx.author.id, "balance", user_wallet["balance"]) await ctx.send(f"**Вы заработали монет!**") @bot.listen("on_command_error") async def cooldown_message(ctx, error): if isinstance(error, commands.CommandOnCooldown): await ctx.send(f"**Вы сможете использовать команду `!` только через секунд-(ы)!**")
Только перед тем как написать эту функцию, импортируйте модуль random.
Таким образом прописав команду earn можно заработать от 60к до 100к монет.
И конечно же команда чтобы давать друг-другу деньги.
@bot.command() async def pay(ctx, user_mention, amount): user_from = ctx.author user_to = get(ctx.guild.members, user_from_wallet = await get_user_wallet(user_from.id) user_to_wallet = await get_user_wallet(user_to.id) amount = int(amount) if amount > user_from_wallet["balance"]: await ctx.send("**У вас нету столько денег, чтобы отдать их другому участнику!**") return user_from_wallet["balance"] -= amount user_to_wallet["balance"] += amount await set_user_wallet(user_from.id, "balance", user_from_wallet["balance"]) await set_user_wallet(user_to.id, "balance", user_to_wallet["balance"]) await ctx.send(f"**Деньги успешно переведины участнику ``**")
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
A Economy Bot made using discord module of python
License
AyushSehrawat/eco-bot
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
A Economy Bot made using py-cord and mongoDB
Install the required modules
pip install -r requirements.txt
Create a file data.json with these contents
Edit market.json for items/products
Database -> eco Collection -> money, bag
- Go to https://www.mongodb.com
- From there register/Try Free ( Fill up the details or register via google )
- Verify Email
- Here for img
Click on project 0 , then click on new project
Click on build database, select Free (for starters), let the default settings be there, but you can chnage the last field of cluster name.
- Then let the default things be selected and enter your username/password ( remember them ).
- In the IP access list enter 0.0.0.0/0 (allow from everywhere).
- Finish and clear
- After that it will take some time to create. Once its finished go to Connect and select Connect your application. Select python and 3.6 or later. Then copy the link and paste in data.json. Edit the password (remove < >too). And done
- Now go to Browse Collections and click Add My Own Data . Enter whatever db and collection name you want to use. Later to connect to that db you can do foo = cluster["database"]["collection"] in the code. Like ecomoney = cluster["eco"]["money"] .
- That's it for db setup.
About
A Economy Bot made using discord module of python