Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add alert functionalities, Convert Currencies #50

Merged
merged 5 commits into from
Oct 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ If you want to run this bot locally, follow these steps:

1. **Clone the Repository** 📂
```bash
git clone https://github.com/yourusername/crypto-bot.git
git clone https://github.com/OpenTekHub/crypto-bot.git
cd crypto-bot

2. **Install Dependencies** 🛠️
Expand Down Expand Up @@ -91,9 +91,13 @@ You should see **"Polling..."**, which means your bot is now running and ready t

Here’s what you can do with the bot:

* **/start**: Initiate the bot 🤖
* **/start**: Initiate the bot and show the main menu 🤖
* **/help**: Get help on how to use the bot 💡
* **/price**: Fetch real-time prices for **Bitcoin, Ethereum, Litecoin** and more! 💰
* **/convert**: Convert cryptocurrencies into different currencies (e.g., `/convert bitcoin usd 1`) 💱
* **/setalert**: Set up price alerts for cryptocurrencies (e.g., `/setalert bitcoin above 60000`) 📈
* **Top 100 Cryptocurrencies**: View a list of the top 100 cryptocurrencies 📊
* **Trending Cryptocurrencies**: Check out the trending cryptocurrencies 🔥
* **Search Cryptocurrency**: Search for specific cryptocurrencies by name 🔍

---

Expand Down
83 changes: 80 additions & 3 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

# Constants
BOT_USERNAME: Final = 'xyz'
BOT_TOKEN: Final = "your token"
BOT_TOKEN: Final = "Your Bot Token"
COINGECKO_API_URL: Final = "https://api.coingecko.com/api/v3"

# Conversation states
Expand Down Expand Up @@ -61,8 +61,9 @@ async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> No
"Welcome to the Crypto Price Bot!\n\n"
"Commands:\n"
"/start - Show main menu\n"
"/help - Show this help message\n\n"
"You can check prices of top cryptocurrencies, view trending coins, or search for a specific cryptocurrency."
"/help - Show this help message\n"
"/convert - Convert Currencies From One To Another\n\n"
"You can check prices of top cryptocurrencies, view trending coins, search for a specific cryptocurrency or Convert them."
)
await update.message.reply_text(help_text)

Expand Down Expand Up @@ -295,6 +296,78 @@ async def error_handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
print(f"Update {update} caused error {context.error}")


# Convert Currency into USD
# Function to fetch crypto price
def get_crypto_price(crypto: str, currency: str = 'usd'):
params = {'ids': crypto, 'vs_currencies': currency}
response = requests.get(COINGECKO_API_URL+'/simple/price', params=params)
data = response.json()
return data.get(crypto, {}).get(currency, 'Price not available')


# Convert crypto to different currencies
async def convert_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if len(context.args) < 3:
await update.message.reply_text("Please use the format: /convert <crypto> <currency> <amount>\n\nFor Example `/convert bitcoin usd 1` - Convert bitcoin price into usd by fettching real time data\n\n")
return
crypto = context.args[0].lower()
currency = context.args[1].lower()
amount = float(context.args[2])
price = get_crypto_price(crypto, currency)
if price != 'Price not available':
converted_amount = price * amount
await update.message.reply_text(f"{amount} {crypto.capitalize()} is worth {converted_amount} {currency.upper()}.")
else:
await update.message.reply_text('Price not available.')


# Add alerts

# Function to set up price alerts
user_alerts = {}

def set_price_alert(user_id, crypto, threshold_price, condition):
user_alerts[user_id] = (crypto, threshold_price, condition)

async def set_alert_command(update: Update, context: ContextTypes.DEFAULT_TYPE):
if len(context.args) < 3:
usage_text = (
"Please use the format: /setalert <crypto> <above|below> <price>\n"
)
await update.message.reply_text(usage_text)
return

crypto = context.args[0].lower() # Get the cryptocurrency (e.g., 'bitcoin')
condition = context.args[1].lower() # Get the condition (e.g., 'above' or 'below')
price = float(context.args[2]) # Get the price threshold

if condition not in ['above', 'below']:
await update.message.reply_text("Please specify 'above' or 'below' for the price alert condition.")
return

user_id = update.message.from_user.id # Get the user's ID

# Save the alert with the condition (above or below)
set_price_alert(user_id, crypto, price, condition)

# Notify the user that the alert has been set
await update.message.reply_text(
f"Price alert set for {crypto.capitalize()} when price is {condition} ${price} USD.\n"
"You'll be notified when this condition is met."
)

async def alert_check(context: ContextTypes.DEFAULT_TYPE):
for user_id, (crypto, threshold_price, condition) in user_alerts.items():
price = get_crypto_price(crypto)

# Check if the condition (above or below) is met
if (condition == 'above' and price >= threshold_price) or (condition == 'below' and price <= threshold_price):
await context.bot.send_message(
chat_id=user_id,
text=f"Price alert! {crypto.capitalize()} has {'exceeded' if condition == 'above' else 'dropped below'} ${threshold_price} USD. Current price: ${price} USD."
)


def main() -> None:
app = Application.builder().token(BOT_TOKEN).build()

Expand All @@ -312,8 +385,12 @@ def main() -> None:
)

app.add_handler(conv_handler)
app.add_handler(CommandHandler('convert', convert_command))
app.add_handler(CommandHandler('setalert', set_alert_command))
app.add_handler(CommandHandler("help", help_command))
app.add_error_handler(error_handler)
# Run alert checker periodically
app.job_queue.run_repeating(alert_check, interval=60)

print('Starting bot...')
app.run_polling(poll_interval=3)
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
python-telegram-bot==20.5
requests==2.31.0
python-telegram-bot[job-queue]