Skip to content

Commit

Permalink
Merge branch 'main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
Varunshiyam authored Oct 29, 2024
2 parents b07531c + 30375ae commit 503ba5e
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 0 deletions.
72 changes: 72 additions & 0 deletions Advanced_Projects/Telegram_Bot/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# Advanced Telegram Bot Project

This project is a feature-rich Telegram bot built using the `python-telegram-bot` library. The bot provides a variety of interactive commands and functionalities, such as weather updates, motivational quotes, and more.

## Features

- **Basic Commands**: Includes `/start`, `/help`, and `/info` commands to guide users.
- **Weather Updates**: Provides real-time weather information for any city, using an external API.
- **Motivational Quotes**: Offers daily motivational quotes with an option to get more via inline buttons.
- **Interactive Elements**: Inline keyboards for quick interactions, making the bot more engaging.
- **Error Handling**: Comprehensive logging and error handling for smooth operation.

## Setup and Installation

### 1. Install Dependencies

Ensure you have Python 3 installed. Then, install the required libraries:

```bash
pip install -r requirements.txt
```

### 2. Get API Keys

- **Telegram Bot API Key**: Create a bot through [BotFather on Telegram](https://core.telegram.org/bots#botfather) and get the token.
- **Weather API Key**: Sign up on [WeatherAPI](https://www.weatherapi.com/) or [OpenWeatherMap](https://openweathermap.org/) to obtain an API key.

### 3. Configure API Keys

Replace placeholders in `app.py` with your actual API keys:

```python
WEATHER_API_KEY = 'your_weather_api_key'
TELEGRAM_TOKEN = 'your_telegram_bot_token'
```

### 4. Run the Bot

Run the bot using:

```bash
python app.py
```

## Usage

Once the bot is running, you can interact with it on Telegram:

- **/start** - Starts the bot and displays a welcome message.
- **/help** - Lists available commands.
- **/weather `<city_name>`** - Retrieves the current weather for a specified city.
- **/motivate** - Sends a motivational quote with an inline option to get more quotes.

## Example Interactions

- `/start`: "Welcome! Use /help to see available commands."
- `/weather London`: "Weather in London: 18°C, Partly Cloudy"
- `/motivate`: "Stay positive, work hard, make it happen!" with a button for more quotes.

## Project Structure

```
├── app.py # Main bot code
├── README.md # Project documentation
└── requirements.txt # Dependencies
```

## Troubleshooting

- **TypeError**: If you encounter issues with the `Updater` class, ensure you're using `Application` instead (for `python-telegram-bot` v20+).
- **Network/API Errors**: Ensure API keys are correctly configured and active.

64 changes: 64 additions & 0 deletions Advanced_Projects/Telegram_Bot/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import logging
import requests
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import Application, CommandHandler, CallbackQueryHandler, ContextTypes

# Enable logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Constants
WEATHER_API_KEY = 'your_weather_api_key'
TELEGRAM_TOKEN = 'your_telegram_bot_token'

# Start command
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text("Welcome! Use /help to see available commands.")

# Help command
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
help_text = "/start - Start the bot\n/help - Get help\n/weather - Get current weather\n/motivate - Get daily motivation"
await update.message.reply_text(help_text)

# Weather command with API integration
async def weather(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
city = ' '.join(context.args) if context.args else 'London'
response = requests.get(f"http://api.weatherapi.com/v1/current.json?key={WEATHER_API_KEY}&q={city}")
if response.status_code == 200:
data = response.json()
weather_info = f"Weather in {data['location']['name']}: {data['current']['temp_c']}°C, {data['current']['condition']['text']}"
await update.message.reply_text(weather_info)
else:
await update.message.reply_text("Could not retrieve weather data.")

# Motivation command with inline keyboard
async def motivate(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
quote = "Stay positive, work hard, make it happen!"
keyboard = [[InlineKeyboardButton("Get Another", callback_data='new_motivation')]]
reply_markup = InlineKeyboardMarkup(keyboard)
await update.message.reply_text(quote, reply_markup=reply_markup)

# Callback for inline button to get new quote
async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
query = update.callback_query
await query.answer()
new_quote = "Believe in yourself and all that you are!"
await query.edit_message_text(text=new_quote)

# Main function to start the bot
def main() -> None:
# Create the Application instance
application = Application.builder().token(TELEGRAM_TOKEN).build()

# Commands
application.add_handler(CommandHandler("start", start))
application.add_handler(CommandHandler("help", help_command))
application.add_handler(CommandHandler("weather", weather))
application.add_handler(CommandHandler("motivate", motivate))
application.add_handler(CallbackQueryHandler(button))

# Start the bot
application.run_polling()

if __name__ == '__main__':
main()
2 changes: 2 additions & 0 deletions Advanced_Projects/Telegram_Bot/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
python-telegram-bot
requests
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
INF = 99

def shortestDist(graph, n, source, target):
dist = [INF] * (n + 1)
path = [-1] * (n + 1)

dist[target] = 0
path[target] = target

for i in range(target - 1, 0, -1):
for j in range(i + 1, n + 1):
if graph[i][j] != INF and dist[i] > graph[i][j] + dist[j]:
dist[i] = graph[i][j] + dist[j]
path[i] = j

if dist[source] == INF:
print(f"There is no path from node {source} to node {target}")
return

print(f"The shortest path distance from node {source} to node {target} is: {dist[source]}")

print("Path:", source, end="")
current = source
while current != target:
current = path[current]
print(f" -> {current}", end="")
print()

def main():
n = int(input("Enter the number of vertices in the graph: "))

graph = [[INF] * (n + 1) for _ in range(n + 1)]

print(f"Enter the adjacency matrix (use {INF} for INF):")
for i in range(1, n + 1):
row = list(map(int, input(f"Row {i}: ").split()))
for j in range(1, n + 1):
graph[i][j] = row[j - 1]

source = int(input("Enter the source node: "))
target = int(input("Enter the target node: "))

shortestDist(graph, n, source, target)

if __name__ == "__main__":
main()
3 changes: 3 additions & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
* [Map](Advanced_Projects/NaviBot-Voice-Assistant/map.py)
* Plagiarism-Checker
* [App](Advanced_Projects/Plagiarism-checker/app.py)
* Telegram Bot
* [App](Advanced_Projects/Telegram_Bot/app.py)

## Algorithms And Data Structures
* Arrays
Expand Down Expand Up @@ -85,6 +87,7 @@
* Medium-Dp-Problems
* [Coin-Change](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/coin-change.py)
* [Longest-Inc-Subseq](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/longest-inc-subseq.py)
* [Multistage-Graph](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/multistage-graph.py)
* [Partition-Subset-Sum](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/partition-subset-sum.py)
* [Unique-Paths](Algorithms_and_Data_Structures/Dynamic-Programming-Series/Medium-DP-Problems/unique-paths.py)
* Heapsort
Expand Down

0 comments on commit 503ba5e

Please sign in to comment.