Вот примерно но для этого не нужен такой сложный код да и эти библиотеки тоже не нужны потому что они у меня не собираются вредить терминала моего для андроида вот так что это короче я сейчас тебе скину код а ты мне напишешь только пару тысяч символов это воспроизводить музыку видеочате типа я в чацкий иду музыкальный файл скидываю в чат а он его воспроизводит уже в видеочате водку. import logging
logging.basicConfig(level=logging.INFO)
from dotenv import load_dotenv
from typing import Optional
from uuid import uuid4
import os
import os.path
import aiofiles
import aiofiles.os
from os import environ
from msspeech import MSSpeech
import asyncio
import aiohttp
from datetime import datetime
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from retry import retry
from bs4 import BeautifulSoup
from expiringdict import ExpiringDict
from pyrogram import Client, filters, compose
from pyrogram.utils import MAX_CHANNEL_ID
from pyrogram.errors import RPCError
from pytgcalls import GroupCallFactory
from pytgcalls.exceptions import GroupCallNotFoundError
load_dotenv()
class MyClient(Client):
async def start(self):
res = await super().start()
await self.get_me()
# next_run_time=datetime.now()
scheduler.add_job(good_morning, 'cron', hour='6')
scheduler.add_job(holidays, 'cron', hour='7')
scheduler.add_job(send_horoscope, 'cron', hour='8')
scheduler.add_job(good_night, 'cron', hour='22')
scheduler.start()
await join_handler()
return res
weretogetherbot_chat_id:int = int(environ["weretogetherbot_chat_id"])
obch_chat_id:int = int(environ["obch_chat_id"])
friends_chat_id:int = int(environ["friends_chat_id"])
full_names = ExpiringDict(max_len=10000, max_age_seconds=3600)
cache5sec = ExpiringDict(max_len=100, max_age_seconds=5)
bot = MyClient("bot", api_id=environ["API_ID"], api_hash=environ["API_HASH"], bot_token=environ["BOT_TOKEN"])
app = Client("phonecalltracker", api_id=environ["API_ID"], api_hash=environ["API_HASH"], lang_code="ru")
weretogetherbot_group_call = GroupCallFactory(app).get_file_group_call('', play_on_repeat=False)
obch_group_call = GroupCallFactory(app).get_file_group_call('', play_on_repeat=False)
friends_group_call = GroupCallFactory(app).get_file_group_call('', play_on_repeat=False)
def get_fid_or_path(path_to_file:str):
fidpath:str = path_to_file+".fid"
fid:str = ""
if os.path.isfile(fidpath) and os.path.getsize(fidpath) > 4:
with open(fidpath) as f:
fid = f.read().strip()
logging.info(fid+" use file ID for"+path_to_file)
return fid
else:
logging.info("use file name for"+path_to_file)
return path_to_file
def set_fid(path_to_file:str, fid:str):
if len(fid) < 4:
raise ValueError("file_id")
if get_fid_or_path(path_to_file) == fid:
logging.info(fid+" there is already such a file id")
return True
fidpath:str = path_to_file+".fid"
with open(fidpath, "w", encoding="UTF-8") as f:
logging.info(fid+" saving file ID for "+path_to_file)
return f.write(fid.strip()) > 1
async def send_scheduler_audio(path_to_file:str, caption=""):
msg = await bot.send_audio(
weretogetherbot_chat_id,
get_fid_or_path(path_to_file),
caption=caption
)
set_fid(path_to_file, msg.audio.file_id)
return msg
async def good_morning():
await send_scheduler_audio("morningsong.mp3", caption="С добрым утром, наша большая семья!")
async def good_night():
await send_scheduler_audio("eveningsong.mp3", caption="Спокойной ночи и приятных сновидений")
async def run_command(*args):
"https://stackoverflow.com/questions/63782892/using-asyncio-to-wait-for-results-from-subprocess"
# Create subprocess
process = await asyncio.create_subprocess_exec(
*args,
# stdout must a pipe to be accessible as process.stdout
stderr=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
)
# Wait for the subprocess to finish
stdout, stderr = await process.communicate()
if stdout is None:
stdout = b""
if stderr is None:
stderr = b""
if process.returncode != 0:
raise CommandError(
f"returncode = {process.returncode}\r\n stdout = {stdout.decode().strip()}\r\n stderr = {stderr.decode().strip()}"
)
# Return stdout
return stdout.decode().strip()
async def audio_to_raw(filename: str, postfix="input.raw") -> str:
new_filename: str = filename+".raw"
new_filename = os.path.join(os.path.dirname(filename), "input.raw")
new_filename = os.path.join(os.path.dirname(filename), postfix)
await run_command(
"ffmpeg", "-i", filename, "-f", "s16le",
"-ac", "2", "-ar", "48000", "-acodec", "pcm_s16le", new_filename, "-y"
)
await aiofiles.os.remove(filename)
return new_filename
async def mp3_to_ogg(filename: str) -> str:
new_filename: str = filename + ".ogg"
await run_command(
"ffmpeg", "-i", filename, "-acodec", "opus", "-strict", "-2", new_filename
)
await aiofiles.os.remove(filename)
return new_filename
async def ffmpeg_concat(files: list, filename: str) -> None:
if len(files) == 0:
raise ValueError("files can't be empty")
pipe = "|".join(files)
return await run_command("ffmpeg", "-i", f"concat:{pipe}", "-c", "copy", filename)
async def speak(text:str, rate:Optional[int]=40, membercount:Optional[int]=-1, voice="ru-RU-SvetlanaNeural")->str:
"Say a voice message and return the path to the file"
mss = MSSpeech()
await mss.set_voice(voice)
await mss.set_rate(rate)
folder = "downloads"
if not os.path.isdir(folder):
await aiofiles.os.mkdir(folder)
filename = os.path.join(folder, str(uuid4())+".mp3")
await mss.synthesize(text.strip(), filename)
filename = await mp3_to_ogg(filename)
if membercount % 10 == 0:
await ffmpeg_concat(["win31.ogg", filename], filename+"10.ogg")
await aiofiles.os.remove(filename)
filename = filename +"10.ogg"
return filename
scheduler = AsyncIOScheduler()
horoscope_cache = ExpiringDict(max_len=2, max_age_seconds=3600*3)
@retry(aiohttp.ClientError, tries=3, delay=6)
@retry(AssertionError, tries=3, delay=6)
async def get_horoscope(w="daily")->str:
if horoscope_cache.get(w):
return horoscope_cache[w]
url:str = f"https://74.ru/horoscope/{w}/"
page:str = ""
result:str = ""
async with aiohttp.ClientSession(headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0"
}) as session:
async with session.get(url) as resp:
page = await resp.text()
assert resp.status == 200
page = page.replace("<", "\n<").replace("<", " <")
soup = BeautifulSoup(page, 'html.parser')
for article in soup.find_all('article', attrs={'class': 'IGRa5'}):
result = result + article.text + "\n\n"
horoscope_cache[w] = result.strip()
return horoscope_cache[w]
def get_full_names(users)->str:
names:List[str] = []
for u in users:
names.append(u.first_name+" "+(u.last_name or ''))
return ", ".join(names)
async def get_full_name_by_id(peer_id:int)->str:
full_name = full_names.get(peer_id, "")
if full_name:
return full_name
u = await app.get_users(peer_id)
full_name = u.first_name
if u.last_name:
full_name = full_name + " " + u.last_name
full_names[peer_id] = full_name
return full_name
@weretogetherbot_group_call.on_network_status_changed
@obch_group_call.on_network_status_changed
@friends_group_call.on_network_status_changed
async def on_network_changed(context, is_connected):
chat_id = MAX_CHANNEL_ID - context.full_chat.id
if is_connected:
logging.info(f'Successfully joined! {chat_id}')
else:
logging.info(f'Disconnected from voice chat... {chat_id}')
async def holidays():
async for message in app.get_chat_history('@kalendar_prazdnikov', limit=2):
if not getattr(message, "photo", False) and "Сегодня" not in message.caption:
continue
await bot.send_message(weretogetherbot_chat_id, message.caption, disable_notification=True)
break
@app.on_message(filters.outgoing & filters.command('join') & filters.chat([weretogetherbot_chat_id, obch_chat_id, friends_chat_id]))
async def join_handler(_=None, message=None):
chat_ids = [message.chat.id,] if message else [weretogetherbot_chat_id, obch_chat_id, friends_chat_id]
try:
if message:
await message.delete()
except RPCError:
logging.exception("delete message error")
if message is not None and message.chat.id not in [weretogetherbot_chat_id, obch_chat_id, friends_chat_id]:
await message.reply('Я работаю только в группах "Мы вместе", "Общалочка" и "Друзья"')
return False
for chat_id in chat_ids:
try:
if chat_id == weretogetherbot_chat_id:
await weretogetherbot_group_call.start(chat_id, enable_action=False)
if chat_id == obch_chat_id:
await obch_group_call.start(chat_id, enable_action=False)
if chat_id == friends_chat_id:
await friends_group_call.start(chat_id, enable_action=False)
except GroupCallNotFoundError:
logging.info(f"{chat_id} Voice chat is not running")
@friends_group_call.on_participant_list_updated
async def friends_participants_are_updated(group_call, participants):
tmpaction:str = ""
text_to_speak:str = ""
for p in participants:
if p.is_self:
continue
if getattr(p.peer, "channel_id", None):
# print("channel", p.peer.channel_id)
# chat_ids.append(p.peer.channel_id)
# print(c)
pass
elif getattr(p.peer, "user_id", None):
if cache5sec.get(p.peer.user_id, None):
continue
cache5sec[p.peer.user_id] = 1
tmpaction = ""
if p.just_joined:
tmpaction = "Присоединяется к видео чату"
elif p.left:
tmpaction = "Покидает видео чат"
if tmpaction:
text_to_speak = "{} {}".format((await get_full_name_by_id(p.peer.user_id)), tmpaction)
voicefile = await speak(text_to_speak, voice="ru-RU-DmitryNeural", rate=0)
group_call.input_filename = ''
voicefile = await audio_to_raw(voicefile, "input3.raw")
group_call.input_filename = voicefile
@obch_group_call.on_participant_list_updated
async def obch_participants_are_updated(group_call, participants):
tmpaction:str = ""
text_to_speak:str = ""
for p in participants:
if p.is_self:
continue
if getattr(p.peer, "channel_id", None):
# print("channel", p.peer.channel_id)
# chat_ids.append(p.peer.channel_id)
# print(c)
pass
elif getattr(p.peer, "user_id", None):
if cache5sec.get(p.peer.user_id, None):
continue
cache5sec[p.peer.user_id] = 1
tmpaction = ""
if p.just_joined:
tmpaction = "Присоединяется к видео чату"
elif p.left:
tmpaction = "Покидает видео чат"
if tmpaction:
text_to_speak = "{} {}".format((await get_full_name_by_id(p.peer.user_id)), tmpaction)
voicefile = await speak(text_to_speak, voice="ru-RU-DmitryNeural", rate=0)
group_call.input_filename = ''
voicefile = await audio_to_raw(voicefile, "input2.raw")
group_call.input_filename = voicefile
@weretogetherbot_group_call.on_participant_list_updated
async def weretogetherbot_participants_are_updated(group_call, participants):
not_send:bool = False
tmpaction:str = ""
text_to_speak:str = ""
for p in participants:
if p.is_self:
continue
if getattr(p.peer, "channel_id", None):
# print("channel", p.peer.channel_id)
# chat_ids.append(p.peer.channel_id)
# print(c)
pass
elif getattr(p.peer, "user_id", None):
if cache5sec.get(p.peer.user_id, None):
continue
cache5sec[p.peer.user_id] = 1
tmpaction = ""
if p.just_joined:
tmpaction = "Присоединяется к видео чату"
not_send = True
elif p.left:
tmpaction = "Покидает видео чат"
not_send = True
if tmpaction:
text_to_speak = "{} {}".format((await get_full_name_by_id(p.peer.user_id)), tmpaction)
voicefile = await speak(text_to_speak, rate=0, voice="ru-RU-DmitryNeural")
if not not_send:
await bot.send_voice(weretogetherbot_chat_id, voicefile, caption=text_to_speak)
group_call.input_filename = ''
voicefile = await audio_to_raw(voicefile)
group_call.input_filename = voicefile
@bot.on_message(filters.command(['start', 'help', 'settings']))
async def start_handler(_, message):
await message.reply("ok")
await message.delete()
@bot.on_message(filters.command('horoscope'))
async def send_horoscope(_=None, message=None):
chat_id = message.chat.id if message else weretogetherbot_chat_id
horoscope_text:str = await get_horoscope()
await bot.send_message(chat_id, horoscope_text)
if message:
await message.delete()
@app.on_message(filters.video_chat_started & filters.chat([obch_chat_id, friends_chat_id]))
async def video_chat_started_message_handler(_, message):
await join_handler(None, message)
@bot.on_message(filters.service & filters.chat(weretogetherbot_chat_id))
async def service_messages_handler(_, message):
text_to_speak:str = ""
members_count:int = -1
if getattr(message, "video_chat_participants_invited", None) is not None:
text_to_speak = "В видео чат приглашается {}".format(get_full_names(message.video_chat_participants_invited))
if getattr(message, "video_chat_scheduled", None) is not None:
text_to_speak = "Запланирован видео чат"
if getattr(message, "video_chat_started", None) is not None:
text_to_speak = "Начался видео чат!"
await join_handler(None, message)
if getattr(message, "video_chat_ended", None) is not None:
text_to_speak = "Видео чат завершён"
if getattr(message, "left_chat_member", None) is not None:
text_to_speak = "{} выходит из группы.".format(message.left_chat_member.first_name + " " + (message.left_chat_member.last_name or ""))
if getattr(message, "new_chat_members", None) is not None:
try:
members_count = await bot.get_chat_members_count(message.chat.id)
except (ValueError, RPCError):
members_count = -1
logging.exception("members count error")
text_to_speak = "Здравствуйте, {}, добро пожаловать в нашу группу! Не стесняйтесь, располагайтесь поудобнее, расскажите о себе! Большая прозьба, не кидайте ссылки на другие группы, иначе будете заблокированы. Приятного вам общения!".format(get_full_names(message.new_chat_members))
if text_to_speak:
voicefile = await speak(text_to_speak, membercount = members_count)
await message.reply_voice(voicefile, caption=text_to_speak)
await aiofiles.os.remove(voicefile)
await message.delete()
if name == "main":
compose([app, bot], sequential=False)