import asyncio
from telethon import TelegramClient, events
from pytgcalls import PyTgCalls, idle
from pytgcalls.types import MediaStream
# Replace these with your API credentials
API_ID = [Redacted PhoneNumber] # Telegram API ID
API_HASH = 'your_api_hash_here' # Telegram API Hash
BOT_TOKEN = 'your_bot_token_here' # Bot Token from BotFather
# Initialize Telethon client
bot = TelegramClient('radio_bot', API_ID, API_HASH).start(bot_token=BOT_TOKEN)
# Initialize PyTgCalls
pytgcalls = PyTgCalls(bot)
# Start the PyTgCalls client
async def start_pytgcalls():
await pytgcalls.start()
# Command to join voice chat and play the radio
@bot.on(events.NewMessage(pattern='/play'))
async def play_radio(event):
# Check if the command was sent in a group or channel
if event.is_group or event.is_channel:
try:
# Replace with the URL of the online radio stream
radio_url = 'https://icecast.radiofrance.fr/fip-midfi.mp3'
# Get the group or channel ID
chat_id = event.chat_id
# Send a message to notify the user
await event.reply("Joining voice chat and playing the radio...")
# Play the radio stream in the voice chat
await pytgcalls.play(
chat_id,
MediaStream(radio_url)
)
await event.reply("Radio is now playing!")
except Exception as e:
await event.reply(f"Failed to play radio: {e}")
else:
await event.reply("This command can only be used in groups or channels.")
# Command to stop playing the radio
@bot.on(events.NewMessage(pattern='/stop'))
async def stop_radio(event):
if event.is_group or event.is_channel:
try:
chat_id = event.chat_id
await pytgcalls.leave(chat_id)
await event.reply("Stopped playing the radio.")
except Exception as e:
await event.reply(f"Failed to stop radio: {e}")
else:
await event.reply("This command can only be used in groups or channels.")
# Start the bot and idle
async def main():
await start_pytgcalls()
await bot.run_until_disconnected()
await idle()
if __name__ == '__main__':
asyncio.run(main())
4. How It Works
Start the Bot:
The bot connects to Telegram using the Telethon client.
PyTgCalls is initialized to manage voice chats.
Play Radio Command:
Use /play in a group or channel where the bot is an admin.
The bot joins the voice chat and streams the provided radio URL.
Stop Radio Command:
Use /stop to stop the stream and leave the voice chat.
5. Prerequisites and Permissions
The bot must be an admin in the group or channel with the ability to manage voice chats.
Ensure the radio URL is a valid audio stream (e.g., MP3 or AAC).
6. Example Radio Streams
Here are some free public radio streams you can use for testing:
FIP Radio (France): https://icecast.radiofrance.fr/fip-midfi.mp3
BBC Radio 1: http://bbcmedia.ic.llnwd.net/stream/bbcmedia_radio1_mf_p
7. Run the Bot
Save the code to a file, e.g., radio_bot.py, and run it:
bash
python radio_bot.py
8. Key Notes
You can customize the bot to handle more commands like pause, resume, or change the volume using the features of PyTgCalls.
If the bot crashes or doesn't join the voice chat, ensure the URL is valid and the group/channel voice chat is active.
This should allow you to create a fully functional bot that streams online radio in Telegram voice chats! 🚀
Yes, the PyTgCalls library is designed to handle online streams, including radio streams or other media streams from URLs. This is evident from the following features and code examples provided in the repository:
How PyTgCalls Handles Online Streams
MediaStream Support:
The library allows you to pass a media URL (e.g., an online stream like an MP3 file or a live audio stream) to the MediaStream class, which is then played in a group or channel voice chat.
This demonstrates that you can provide a URL to an online media file or stream (such as a radio stream) to play it in a voice chat.
FFmpeg Integration:
The library integrates with FFmpeg, a powerful tool for processing media streams. This allows it to handle complex media formats, online streams, and even live streams.
The ffmpeg.py file in the repository shows how the library uses FFmpeg to validate streams and extract audio/video parameters:
This means PyTgCalls can process online streams and adapt them for playback in Telegram voice chats.
Stream Checking:
The library checks the validity of the media stream using FFmpeg before playing it, ensuring the URL is accessible and the stream has audio or video components.
It raises exceptions like NoAudioSourceFound, NoVideoSourceFound, or LiveStreamFound if the stream is invalid or unsupported.
Real-Time Playback:
The play() method in PyTgCalls supports real-time playback of media streams in voice chats. This includes continuous streams (e.g., radio) as well as pre-recorded media files.
What Types of Online Streams Can PyTgCalls Handle?
Audio Streams:
Online radio streams (e.g., MP3, AAC, or other supported formats).