How to send a message via chat ID? - python

I have a script, it has inline buttons that, when clicked in a group chat, send a message to private messages.
I would like to try so that they send in response to pressing the inline button by chat id
If possible, write me where and how to add sending a message via chat id
For these messages, I need to change the sending to the chat id: https://imgur.com/a/RdXSb7E
PS: here is the chat id (-1001479485376)
import logging
import asyncio
from aiogram import Bot, Dispatcher, executor, types
from aiogram.utils.markdown import hbold, hunderline, hcode, hlink
API_TOKEN = 'token'
# Configure logging
logging.basicConfig(level=logging.INFO)
# Initialize bot and dispatcher
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
#dp.message_handler(commands='cat')
async def send_welcome(message: types.Message):
# So... At first I want to send something like this:
await message.reply("Вы хотите видеть много кисок? Вы готовы? 😏")
# Wait a little...
await asyncio.sleep(1)
# Good bots should send chat actions...
await types.ChatActions.upload_photo()
# Create media group
media = types.MediaGroup()
# Attach local file
media.attach_photo(types.InputFile('data/cat.jpg'), 'Cat!')
# More local files and more cats!
media.attach_photo(types.InputFile('data/cats.jpg'), 'More cats!')
# You can also use URL's
# For example: get random puss:
media.attach_photo('http://lorempixel.com/400/200/cats/', 'Random cat.')
# And you can also use file ID:
# media.attach_photo('<file_id>', 'cat-cat-cat.')
# Done! Send media group
await message.reply_media_group(media=media)
#dp.message_handler(commands='dog')
async def send_welcome(message: types.Message):
# So... At first I want to send something like this:
await message.reply("Вы хотите видеть много собачек? Вы готовы? 😏")
# Wait a little...
await asyncio.sleep(1)
# Good bots should send chat actions...
await types.ChatActions.upload_photo()
# Create media group
media = types.MediaGroup()
# Attach local file
media.attach_photo(types.InputFile('data/c2b.jpg'), 'Dog!')
# More local files and more cats!
media.attach_photo(types.InputFile('data/c2a.jpg'), 'More dog!')
media.attach_photo(types.InputFile('data/c2w.gif'), 'More dogs!')
# Done! Send media group
await message.reply_media_group(media=media)
#dp.message_handler(commands='music')
async def send_welcome(message: types.Message):
# So... At first I want to send something like this:
await message.reply("Вот и музычка подъехала! Вы готовы? 😏")
# Wait a little...
await asyncio.sleep(1)
await types.ChatActions.upload_photo()
# Create media group
media = types.MediaGroup()
media.attach_audio(types.InputFile('data/ChillOut.mp3'), 'Music!')
media.attach_audio(types.InputFile('data/REIMANN TEAM.mp3'), 'Music2!')
media.attach_audio(types.InputFile('data/Mister Robot Поёт.mp3'), 'Music3!')
# Done! Send media group
await message.reply_media_group(media=media)
#dp.message_handler(commands='bot')
async def start_cmd_handler(message: types.Message):
keyboard_markup = types.InlineKeyboardMarkup(row_width=3)
# default row_width is 3, so here we can omit it actually
# kept for clearness
text_and_data = (
('Помощь 🧞', 'Помощь 🧞'),
('Правила ⚔️', 'Правила ⚔️'),
('Мануалы 🧸', 'Мануалы 🧸'),
)
# in real life for the callback_data the callback data factory should be used
# here the raw string is used for the simplicity
row_btns = (types.InlineKeyboardButton(text, callback_data=data) for text, data in text_and_data)
keyboard_markup.row(*row_btns)
keyboard_markup.add(
# url buttons have no callback data
types.InlineKeyboardButton('ReimannLogs 🔱', url='https://t.me/reimannlogs_bot'),
)
await message.reply("Здравствуй, сударь! 👋🏻\nС чем тебе нужна помощь?", reply_markup=keyboard_markup)
# Use multiple registrators. Handler will execute when one of the filters is OK
#dp.callback_query_handler(text='Правила ⚔️') # if cb.data == 'no'
#dp.callback_query_handler(text='Помощь 🧞') # if cb.data == 'yes'
#dp.callback_query_handler(text='Мануалы 🧸')
async def inline_kb_answer_callback_handler(query: types.CallbackQuery):
answer_data = query.data
# always answer callback queries, even if you have nothing to say
await query.answer(f'Вы выбрали пункт {answer_data!r}')
if answer_data == 'Помощь 🧞':
text = "Есть какие-то вопросы? 🛎\n \nВот реквезиты:\n \nПо всем вопросам: #FollHash ☯️\nПо всем вопросам, заявкам в тиму: #t3sse ☯️\n \nВот полезные команды, для развлекухи:\n \n/cat - киски 😏\n/dog - собачки 🦮\n/music - музычка 🌆"
elif answer_data == 'Правила ⚔️':
text = """Пᴩᴀʙиᴧᴀ чᴀᴛᴀ 💻
=======================
Зᴀᴨᴩᴇщᴇнᴏ: 🚫
- ᴧюбᴀя ᴋᴏʍʍᴇᴩция ʙ чᴀᴛᴇ (ᴨᴏᴋуᴨᴋᴀ/ᴨᴩᴏдᴀжᴀ)
- уᴋᴀɜыʙᴀᴛь иᴧи ᴨᴏʍᴇчᴀᴛь дᴩуᴦиᴇ ᴋᴀнᴀᴧы иᴧи бᴏᴛы
- ᴩᴇᴋᴧᴀʍᴀ иᴧи уᴨᴏʍинᴀниᴇ ᴨᴏхᴏжих ᴩᴇᴄуᴩᴄᴏʙ/ɯᴏᴨᴏʙ/нᴇйʍᴏʙ ʙ ᴧюбᴏʍ ᴋᴏнᴛᴇᴋᴄᴛᴇ
- ᴨᴏᴨᴩᴏɯᴀйничᴇᴄᴛʙᴏ
- ɜᴧᴏуᴨᴏᴛᴩᴇбᴧᴇниᴇ "CAPS LOCK"
- ʙᴇᴄᴛи ᴄᴇбя нᴇᴀдᴇᴋʙᴀᴛнᴏ ʙ чᴀᴛᴇ и ᴩᴀɜʙᴏдиᴛь "ᴄᴩᴀч"
- ᴏᴄᴋᴏᴩбᴧᴇниᴇ "мᴏдᴇᴩᴀции/ᴨᴩᴏᴇᴋᴛᴀ/ɯᴏᴨᴀ" - бᴀн ❗️
- ᴏᴛᴨᴩᴀʙᴧяᴛь ᴄᴋᴩиʍᴇᴩы, ᴩᴀᴄчᴧᴇнᴇнᴋу, ᴄʙᴀᴄᴛиᴋу, нᴀциɜʍ, ᴋᴏнᴛᴇнᴛ 🔞
- ᴏɸᴏᴩʍᴧяᴛь ᴩᴀɜᴧичныᴇ ᴋᴀᴩᴛы, ᴀбуɜиᴛь ᴩᴇɸᴇᴩᴀᴧьную ᴄиᴄᴛᴇʍу, ᴄᴋᴀʍ и ᴏбʍᴀн ᴨᴏᴧьɜᴏʙᴀᴛᴇᴧᴇй
- ᴨᴩᴏᴨᴀᴦᴀндᴀ ᴨᴏᴧиᴛиᴋи
- ɸᴧуд\ᴄᴨᴀʍ ᴏдинᴀᴋᴏʙыʍи ɜᴀ ᴋᴏнᴛᴇᴋᴄᴛᴏʍ ᴄᴧᴏʙᴀʍи иᴧи ᴨᴩᴇдᴧᴏжᴇнияʍи (1 ᴨᴩᴇдуᴨᴩᴇждᴇниᴇ, ᴨᴏᴄᴧᴇ - ɯᴛᴩᴀɸ) """
elif answer_data == 'Мануалы 🧸':
text = "Краткий мануал о том как обрабатывать логи - https://telegra.ph/Kak-obrabatyvat-logi-05-30\nЗа привлечение новой аудитории, выдаю логи🥳"
else:
text = f'Unexpected callback data {answer_data!r}!'
await bot.send_message(query.from_chat.id, text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)

Just change await bot.send_message(query.from_chat.id, text) to await bot.send_message(-1001479485376, text). See the docs here.

Related

Callback query handler in bot doesn't call

I write telegram bot with aiogram
There's the function:
async def create_bill(message:types.Message, state: FSMContext):
if message.text.isdigit():
amount = int(message.text)
await message.answer('Создаю счет для оплаты...')
logging.logger_info.info('Создается счет')
bill = p2p.bill(bill_id=message.from_user.id+1, amount=amount, lifetime=5)
payment_url = p2p.check(bill_id=message.from_user.id+1).pay_url
pkb_btn_1 = InlineKeyboardButton('Оплатить', url=payment_url)
pkb_btn_2 = (InlineKeyboardButton(text="Зачислить на счет", callback_data='update_balance'))
pkb_mark_1 = InlineKeyboardMarkup.add(pkb_btn_1)
pkb_full = InlineKeyboardMarkup(row_width=2).add(pkb_btn_1)
pkb_full.add(pkb_btn_2)
logging.logger_info.info(f'Создан счет #{bill.bill_id} на сумму {amount} для пользователя {message.from_user.id}')
await message.answer('Счет создан!\nНажмите на кнопку, чтобы оплатить', reply_markup=pkb_full)
await UserStates.next()
else:
await message.answer('Пожалуйста, введите число!')
logging.logger_info.info(f'Пользователь {message.from_user.id} ввел некорректные данные')
It works and awaiting the inline keyboard with 2 buttons. First button is just a link (it works), second button should to call this handler:
#dp.callback_query_handler(lambda c: c.data == 'update_balance')
async def process_callback_balance_update(callback_query: types.CallbackQuery, state='*'):
if user.get_user_block_status(callback_query.from_user.id):
await callback_query.message.answer('Вы были заблокированы')
logging.logger_warn.warning(f'Заблокированный пользователь {callback_query.from_user.id} пытался подключиться к боту!')
else:
if p2p.check(bill_id=callback_query.from_user.id+1).status != 'PAID':
await callback_query.message.answer('Оплата не прошла!')
logging.logger_warn.warning(f'Пользователь {callback_query.from_user.id} пытался пополнить баланс с неоплаченным счетом!')
else:
current_balance = user.get_user_balance(callback_query.from_user.id)
new_balance = current_balance + p2p.check(bill_id=callback_query.from_user.id+1).amount
logging.logger_info.info(f'Производится зачисление средств на баланс пользователя {callback_query.from_user.id}')
await user.change_user_balance(callback_query.from_user.id, new_balance)
await callback_query.message.answer('Деньги зачислены')
await state.finish()
logging.logger_info.info(f'Деньги зачислены. Баланс пользователя {new_balance}')
await callback_query.answer()
But it's doesn't call handler!
I tried to add/remove state, replace this handler in another place in code, but nothing!
In logs I see this:
aiogram.contrib.middlewares.logging - INFO - Unhandled callback query [ID:1342058245786784398] from user [ID:312472285] for message [ID:621] in chat [private:312472285] with data: users originally posted by user [ID:5621517130]
I read almost all in google, read the docs and examples, tried different ways, but is still doesn't work
Also I have another handler wrote definitely same way and in works correctly

How do i add handler to InlineKeyboardButton, so i can use data from message ubove it?

I gather data from Firebase Realtime Database and send it to Telegram bot as messages with buttons, that use varaiables from message used.
I want to catch the two variables longitude and latitude, then use it in the function lower, how can i do that?
#dp.message_handler(Text(equals='Get Maps'))
async def get_maps(message: types.Message):
await message.answer('Please wait a bit...')
data = collect_maps()
keyboard = types.InlineKeyboardMarkup()
key = types.InlineKeyboardButton('Get Location', callback_data='Get Location')
keyboard.add(key)
await message.answer('Your maps, that i collected:')
for index, item in enumerate(data):
card = f'{index+1}) {item.get("id")} - {item.get("name")}\n' \
f'Longitude: {item.get("longitude")}\n' \
f'Latitude: {item.get("latitude")}\n'
await message.answer(card, reply_markup=keyboard)
Message and button

How to delay aiogram command?

I have inline buttons with a response to them, some people spam them, I would like to make a delay for the command.
How to implement this?
If possible, write another way to answer the user that the command can be written after a while
#dp.callback_query_handler(id, text='Правила ⚔️')
#dp.callback_query_handler(id, text='Мануалы 🧸')
async def inline_kb_answer_callback_handler(query: types.CallbackQuery):
answer_data = query.data
# always answer callback queries, even if you have nothing to say
await query.answer(f'Вы выбрали пункт {answer_data!r}')
if answer_data == 'Помощь 🧞':
text = "Есть какие-то вопросы? 🛎\n \nПо вопросам внутри чата:\n \n Сотрудничество - #reimannlive 🈺 \n \nПо всем вопросам: #FollHash ☯️\nПо всем вопросам, заявкам в тиму: #t3sse ☯️\n \nВот полезные команды, для развлекухи:\n \n/cat - киски 😏\n/dog - собачки 🦮\n/music - музычка 🌆\n/robot - бредовый видосик 🤣"
elif answer_data == 'Правила ⚔️':
text = """Пᴩᴀʙиᴧᴀ чᴀᴛᴀ 💻
=======================
Зᴀᴨᴩᴇщᴇнᴏ: 🚫
- ᴧюбᴀя ᴋᴏʍʍᴇᴩция ʙ чᴀᴛᴇ (ᴨᴏᴋуᴨᴋᴀ/ᴨᴩᴏдᴀжᴀ)
- уᴋᴀɜыʙᴀᴛь иᴧи ᴨᴏʍᴇчᴀᴛь дᴩуᴦиᴇ ᴋᴀнᴀᴧы иᴧи бᴏᴛы
- ᴩᴇᴋᴧᴀʍᴀ иᴧи уᴨᴏʍинᴀниᴇ ᴨᴏхᴏжих ᴩᴇᴄуᴩᴄᴏʙ/ɯᴏᴨᴏʙ/нᴇйʍᴏʙ ʙ ᴧюбᴏʍ ᴋᴏнᴛᴇᴋᴄᴛᴇ
- ᴨᴏᴨᴩᴏɯᴀйничᴇᴄᴛʙᴏ
- ɜᴧᴏуᴨᴏᴛᴩᴇбᴧᴇниᴇ "CAPS LOCK"
- ʙᴇᴄᴛи ᴄᴇбя нᴇᴀдᴇᴋʙᴀᴛнᴏ ʙ чᴀᴛᴇ и ᴩᴀɜʙᴏдиᴛь "ᴄᴩᴀч"
- ᴏᴄᴋᴏᴩбᴧᴇниᴇ "мᴏдᴇᴩᴀции/ᴨᴩᴏᴇᴋᴛᴀ/ɯᴏᴨᴀ" - бᴀн ❗️
- ᴏᴛᴨᴩᴀʙᴧяᴛь ᴄᴋᴩиʍᴇᴩы, ᴩᴀᴄчᴧᴇнᴇнᴋу, ᴄʙᴀᴄᴛиᴋу, нᴀциɜʍ, ᴋᴏнᴛᴇнᴛ 🔞
- ᴏɸᴏᴩʍᴧяᴛь ᴩᴀɜᴧичныᴇ ᴋᴀᴩᴛы, ᴀбуɜиᴛь ᴩᴇɸᴇᴩᴀᴧьную ᴄиᴄᴛᴇʍу, ᴄᴋᴀʍ и ᴏбʍᴀн ᴨᴏᴧьɜᴏʙᴀᴛᴇᴧᴇй
- ᴨᴩᴏᴨᴀᴦᴀндᴀ ᴨᴏᴧиᴛиᴋи
- ɸᴧуд\ᴄᴨᴀʍ ᴏдинᴀᴋᴏʙыʍи ɜᴀ ᴋᴏнᴛᴇᴋᴄᴛᴏʍ ᴄᴧᴏʙᴀʍи иᴧи ᴨᴩᴇдᴧᴏжᴇнияʍи (1 ᴨᴩᴇдуᴨᴩᴇждᴇниᴇ, ᴨᴏᴄᴧᴇ - ɯᴛᴩᴀɸ) """
elif answer_data == 'Мануалы 🧸':
text = "Краткий мануал о том как обрабатывать логи - https://telegra.ph/Kak-obrabatyvat-logi-05-30\nЗа привлечение новой аудитории, выдаю логи🥳"
else:
text = f'Unexpected callback data {answer_data!r}!'
await bot.send_message(ID, text)
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
I hope you can help me, thanks in advance!
aiogram has a flood avoidance (anti flood) example, which basically prevents users from misusing the command. remember to install (aiohttp, aioredis and redis) on your server.
import asyncio
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.fsm_storage.redis import RedisStorage2
from aiogram.dispatcher import DEFAULT_RATE_LIMIT
from aiogram.dispatcher.handler import CancelHandler, current_handler
from aiogram.dispatcher.middlewares import BaseMiddleware
from aiogram.utils.exceptions import Throttled
TOKEN = 'BOT_TOKEN_HERE'
# In this example Redis storage is used
storage = RedisStorage2(db=5)
bot = Bot(token=TOKEN)
dp = Dispatcher(bot, storage=storage)
def rate_limit(limit: int, key=None):
"""
Decorator for configuring rate limit and key in different functions.
:param limit:
:param key:
:return:
"""
def decorator(func):
setattr(func, 'throttling_rate_limit', limit)
if key:
setattr(func, 'throttling_key', key)
return func
return decorator
class ThrottlingMiddleware(BaseMiddleware):
"""
Simple middleware
"""
def __init__(self, limit=DEFAULT_RATE_LIMIT, key_prefix='antiflood_'):
self.rate_limit = limit
self.prefix = key_prefix
super(ThrottlingMiddleware, self).__init__()
async def on_process_message(self, message: types.Message, data: dict):
"""
This handler is called when dispatcher receives a message
:param message:
"""
# Get current handler
handler = current_handler.get()
# Get dispatcher from context
dispatcher = Dispatcher.get_current()
# If handler was configured, get rate limit and key from handler
if handler:
limit = getattr(handler, 'throttling_rate_limit', self.rate_limit)
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
else:
limit = self.rate_limit
key = f"{self.prefix}_message"
# Use Dispatcher.throttle method.
try:
await dispatcher.throttle(key, rate=limit)
except Throttled as t:
# Execute action
await self.message_throttled(message, t)
# Cancel current handler
raise CancelHandler()
async def message_throttled(self, message: types.Message, throttled: Throttled):
"""
Notify user only on first exceed and notify about unlocking only on last exceed
:param message:
:param throttled:
"""
handler = current_handler.get()
dispatcher = Dispatcher.get_current()
if handler:
key = getattr(handler, 'throttling_key', f"{self.prefix}_{handler.__name__}")
else:
key = f"{self.prefix}_message"
# Calculate how many time is left till the block ends
delta = throttled.rate - throttled.delta
# Prevent flooding
if throttled.exceeded_count <= 2:
await message.reply('Too many requests! ')
# Sleep.
await asyncio.sleep(delta)
# Check lock status
thr = await dispatcher.check_key(key)
# If current message is not last with current key - do not send message
if thr.exceeded_count == throttled.exceeded_count:
await message.reply('Unlocked.')
#dp.message_handler(commands=['start'])
#rate_limit(5, 'start') # this is not required but you can configure throttling manager for current handler using it
async def cmd_test(message: types.Message):
# You can use this command every 5 seconds
await message.reply('Test passed! You can use this command every 5 seconds.')
if __name__ == '__main__':
# Setup middleware
dp.middleware.setup(ThrottlingMiddleware())
# Start long-polling
executor.start_polling(dp)

How to send a message and an embed when streamer is live? | Error | Discord.py

I have written the code to check if Twitch streamer is life, if so send a message, but i can't find a way to check if life notification(message and embed) is already send. So I tried different things of checking embed title: if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}") == embed: and if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}"):. But in the first case bot is spamming, in the second case bot doesn't activate else statement(which i need to send notification), so i am getting spammed or instead bot doesn't send anything at all. Please help me: I need balance, when streamer is live send ONE notification and then break(then check only if statement which must prevent bot from spamming. Here is the CODE. I recommend you taking a look between line 74 and 119. Especially line 99 with if statement.
import os
import json
import discord
import requests
from discord.ext import tasks, commands
from discord.utils import get
from server import ping
from Time import mytimemy
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='$', intents=intents)
TOKEN = os.getenv('token')
# Authentication with Twitch API.
client_id = os.getenv('client_id')
client_secret = os.getenv('Dweller_token')
body = {
'client_id': client_id,
'client_secret': client_secret,
"grant_type": 'client_credentials'
}
r = requests.post('https://id.twitch.tv/oauth2/token', body)
keys = r.json()
headers = {
'Client-ID': client_id,
'Authorization': 'Bearer ' + keys['access_token']
}
'''user_info = twitch.get_users(logins=['turb4ik'])
user_id = user_info['data'][0]['id']
print(user_info)'''
# Returns true if online, false if not.
def checkuser(streamer_name):
stream = requests.get('https://api.twitch.tv/helix/streams?user_login=' + streamer_name, headers=headers)
stream_data = stream.json()
if len(stream_data['data']) == 1:
return True, stream_data
else:
return False, stream_data
# Executes when bot is started
#bot.event
async def on_ready():
# Defines a loop that will run every 10 seconds (checks for live users every 10 seconds).
#tasks.loop(seconds=10)
async def live_notifs_loop():
# username = stream_data['data'][0]['user_name']
# stream_title = stream_data['data'][0]['title']
# game_being_played = stream_data['data'][0]['game_name']
# Opens and reads the json file
with open('streamers.json', 'r') as file:
streamers = json.loads(file.read())
# Makes sure the json isn't empty before continuing.
if streamers is not None:
# Gets the guild, 'twitch streams' channel, and streaming role.
guild = bot.get_guild(690995360411156531)
channel = bot.get_channel(785523710362124298)
role = get(guild.roles, id=835581408272580649)
# Loops through the json and gets the key,value which in this case is the user_id and twitch_name of
# every item in the json.
for user_id, twitch_name in streamers.items():
print("Checking" + " " + str(twitch_name) + " Current time: " + str(mytimemy()))
# Takes the given twitch_name and checks it using the checkuser function to see if they're live.
# Returns either true or false.
status, stream_data = checkuser(twitch_name)
# Gets the user using the collected user_id in the json
user = bot.get_user(int(user_id))
# Makes sure they're live
if status is True:
# Checks to see if the live message has already been sent.
async for message in channel.history(limit=200):
twitch_embed = discord.Embed(
title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}",
color=0xac1efb,
url=f'\nhttps://www.twitch.tv/{twitch_name}'
)
twitch_embed.add_field(
name = '**Game**',
value = stream_data['data'][0]['game_name'],
inline = True
)
twitch_embed.add_field(
name = '**Viewers**',
value = stream_data['data'][0]['viewer_count'],
inline = True
)
twitch_embed.set_author(
name = str(twitch_name),
icon_url = stream_data['data'][0]['thumbnail_url']
)
twitch_embed.set_image(url = f'https://www.twitch.tv/{twitch_name}')
embeds = message.embeds
for embed in embeds:
if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}") == embed:
try:
embed_title = twitch_embed.title
embed_description = twitch_embed.description
except Exception as e:
break
print(f"Already sent for {user.name} at {mytimemy()}!") #just sending the time and name
break
else:
# Gets all the members in your guild.
async for member in guild.fetch_members(limit=None):
# If one of the id's of the members in your guild matches the one from the json and
# they're live, give them the streaming role.
if member.id == int(user_id):
await member.add_roles(role)
# Sends the live notification to the 'twitch streams' channel then breaks the loop.
await channel.send(
content = f"Hey #everyone! {user.name} is now streaming on Twitch! Go check it out: https://www.twitch.tv/{twitch_name}", embed=twitch_embed)
print(f"{user} started streaming. Sending a notification.")
break
# If they aren't live do this:
else:
# Gets all the members in your guild.
async for member in guild.fetch_members(limit=None):
# If one of the id's of the members in your guild matches the one from the json and they're not
# live, remove the streaming role.
if member.id == int(user_id):
await member.remove_roles(role)
# Checks to see if the live notification was sent.
async for message in channel.history(limit=200):
try:
embed_title = message.embeds[0].title
embed_description = message.embeds[0].description
except Exception as e:
break
# If it was, delete it.
if str(user.name) in embed_title and "is now streaming" in embed_title:
print(f"{user} stopped streaming. Removing the notification.")
await message.delete()
# Start your loop.
live_notifs_loop.start()
# Command to add Twitch usernames to the json.
#bot.command(name='addtwitch', help='Adds your Twitch to the live notifs.', pass_context=True)
async def add_twitch(ctx, twitch_name):
# Opens and reads the json file.
with open('streamers.json', 'r') as file:
streamers = json.loads(file.read())
# Gets the users id that called the command.
user_id = ctx.author.id
# Assigns their given twitch_name to their discord id and adds it to the streamers.json.
streamers[user_id] = twitch_name
# Adds the changes we made to the json file.
with open('streamers.json', 'w') as file:
file.write(json.dumps(streamers))
# Tells the user it worked.
await ctx.send(f"Added {twitch_name} for {ctx.author} to the notifications list.")
ping()
print('Server Running')
bot.run(TOKEN)
It is very hard to explain and understand, but please help me. I need to check embed content while someone is streaming, so the embed and message are send one time per stream and NO spamming. And when stream goes off forget that embed content, so the embed can be send next time too. If u don't understand something, please ask. My discord just in case: Dweller_Igor#3291. Please someone EDIT the question, if it helps you better understand it.
MINIMAL REPRODUCIBLE EXAMPLE (embed, if-statement and else-statement):
if status is True:
# Checks to see if the live message has already been sent.
async for message in channel.history(limit=200):
twitch_embed = discord.Embed(
title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}",
color=0xac1efb,
url=f'\nhttps://www.twitch.tv/{twitch_name}'
)
twitch_embed.add_field(
name = '**Game**',
value = stream_data['data'][0]['game_name'],
inline = True
)
twitch_embed.add_field(
name = '**Viewers**',
value = stream_data['data'][0]['viewer_count'],
inline = True
)
twitch_embed.set_author(
name = str(twitch_name),
icon_url = stream_data['data'][0]['thumbnail_url']
)
twitch_embed.set_image(url = f'https://www.twitch.tv/{twitch_name}')
embeds = message.embeds
for embed in embeds:
if discord.Embed(title=f":red_circle: **LIVE**\n{user.name} is now streaming on Twitch! \n \n {stream_data['data'][0]['title']}") == embed:
try:
embed_title = twitch_embed.title
embed_description = twitch_embed.description
except Exception as e:
break
print(f"Already sent for {user.name} at {mytimemy()}!") #just sending the time and name
break
else:
# Gets all the members in your guild.
async for member in guild.fetch_members(limit=None):
# If one of the id's of the members in your guild matches the one from the json and
# they're live, give them the streaming role.
if member.id == int(user_id):
await member.add_roles(role)
# Sends the live notification to the 'twitch streams' channel then breaks the loop.
await channel.send(
content = f"Hey #everyone! {user.name} is now streaming on Twitch! Go check it out: https://www.twitch.tv/{twitch_name}", embed=twitch_embed)
print(f"{user} started streaming. Sending a notification.")
break
await ctx.send(content = "some message", embed = embed)
It was a very stupid question at the time, and it still is to this day

Sending a variable to discord channel Python

So I have this code:
while True:
recent_post = api.user_timeline(screen_name = 'PartAlert', count = 1, since_id=recent_id, include_rts = True, tweet_mode='extended')
if recent_post:
last_post = recent_post[0].full_text
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_#.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', last_post)
if urls:
print(f"[{datetime.datetime.now()}] Link(s) Found:")
for x in range(len(urls)):
if urls[x][-1] == ':':
urls[x] = urls[x][:-1]
print(urls[x])
recent_id = recent_post[0].id
time.sleep(10)
which gets the twitter post of a specific user. What I want now is that the url variable will send to a discord channel but whatever I try it doesnt work. Any ideas?
Be sure to place the send_url method above the line in which you call send_url (or you could use classes, but that might require redesigning your bot).
To send messages to a channel, you can use:
channel_id = # some channel id here
message = # some message here
channel = client.get_channel(channel_id)
await channel.send(message)
You could also define send_url like so
async def send_url(channel_id, message):
channel = client.get_channel(channel_id)
await channel.send(message)
Just be sure to place it above the line in which you call the method.

Categories

Resources