if (message.Text.ToLower().Contains("старт"))
{
var rand = new Random();
var photos = new string[] { "http://example.com/photo1.jpg", "http://example.com/photo2.jpg" }; // Замените URL-адресами ваших фотографий
var photoUrl = photos[rand.Next(photos.Length)];
if (!string.IsNullOrEmpty(photoUrl))
{
var photo = new InputOnlineFile(photoUrl);
await client.SendPhotoAsync(message.Chat.Id, photo);
}
else
{
// Обработка случая, когда отсутствуют доступные фотографии
await client.SendTextMessageAsync(message.Chat.Id, "Извините, нет доступных фотографий.");
}
}
@bot.message_handler(commands=['kosti'])
def kosti(message: types.Message):
bot.send_message(message.from_user.id, f"Ну, что, {message.from_user.username}, сыграем в кости!")
sleep(1)
bot_data = bot.send_dice(message.from_user.id).dice.value
sleep(4)
user_data = bot.send_dice(message.from_user.id).dice.value
sleep(4)
if bot_data > user_data:
bot.send_message(message.from_user.id, "Вы проиграли боту в кубики(")
bmoney -= 1000
elif bot_data < user_data:
bot.send_message(message.from_user.id, "Вы выиграли)")
bmoney += 5000
else:
bot.send_message(message.from_user.id, "Ничья!")
from telegram import InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CallbackQueryHandler
def start(update, context):
keyboard = [[InlineKeyboardButton("Нажми меня", callback_data='oxota')]]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text('Привет! Нажми кнопку:', reply_markup=reply_markup)
def button(update, context):
query = update.callback_query
if query.data == 'oxota':
photo_path = r"C:\Users\Вадим\Downloads\msg5595864732-34949.jpg"
caption = 'Содержимое:\nTehthesththththht'
with open(photo_path, 'rb') as photo:
query.message.reply_photo(photo=photo, caption=caption)
updater = Updater('YOUR_TOKEN', use_context=True)
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.start_polling()
updater.idle()
using UnityEngine;
public class Bullet : MonoBehaviour
{
private Rigidbody2D rb;
private float speed = 7f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = transform.right * speed; // Используем velocity для движения пули
Destroy(gameObject, 3f); // Уничтожаем пулю через 3 секунды (на ваше усмотрение)
}
}
using UnityEngine;
public class Bullet : MonoBehaviour
{
private Rigidbody2D rb;
private float speed = 7f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.AddForce(transform.right * speed, ForceMode2D.Impulse); // Используем AddForce для движения пули
Destroy(gameObject, 3f); // Уничтожаем пулю через 3 секунды (на ваше усмотрение)
}
}
import { onMounted } from 'vue'
onMounted(() => {
window.Telegram.WebApp.MainButton.show()
window.Telegram.WebApp.onEvent('mainButtonClicked', handleMainButtonClick)
})
const handleMainButtonClick = () => {
// Обработка события нажатия на кнопку "mainButton"
console.log('Нажата кнопка mainButton')
// Дополнительные действия, которые вы хотите выполнить при нажатии на кнопку
}
from selenium import webdriver
from selenium.webdriver.support.select import Select
# Инициализация драйвера
driver = webdriver.Chrome()
# Открытие веб-страницы
driver.get("https://example.com")
# Нахождение элемента выпадающего списка
dropdown = driver.find_element(By.XPATH, '//*[@id="block-content"]/div/article/div[1]/table[3]/tbody/tr[1]/td[2]/select')
# Создание объекта класса Select
select = Select(dropdown)
# Выбор опции по тексту
select.select_by_visible_text("Шапокляк")
# Закрытие драйвера
driver.quit()
from telebot import TeleBot, types
from datetime import datetime
from threading import Thread
from time import sleep
bot = TeleBot(token=token)
posts = {}
action = ''
new_post = []
def sleep_poster(date_post, message):
while True:
if date_post < datetime.now():
print('Отправили сообщение!')
if message[3] is None:
bot.send_message(message[0], message[1], reply_markup=message[2], parse_mode='Markdown')
else:
with open(message[3], 'rb') as f:
bot.send_photo(message[0], f, caption=message[1], reply_markup=message[2])
return
else:
sleep(60)
@bot.message_handler(commands=['start'])
def start_command(message):
user = message.chat.id
if user == adm_id:
rp = types.ReplyKeyboardMarkup(True)
rp.row('Новый пост')
bot.send_message(user, 'Привет, используй кнопки для работы с ботом.', reply_markup=rp)
@bot.message_handler(content_types=['text', 'photo'])
def text(message):
global action, new_post
user = message.chat.id
if message.text == 'Новый пост':
if user == adm_id:
bot.send_message(user, 'Введите текст для сообщения. Используй для *жирного текста*, _курсива_')
action = 'text'
new_post = []
elif action == 'text':
new_post.append(message.text)
action = 'buttons'
bot.send_message(user, 'Теперь введите кнопки по шаблону "Имя кнопки; ссылка.ru, '
'Имя второй кнопки; example.com" (без ковычек). Ряды разделяются Enter`ом.')
elif action == 'buttons':
keyboard = types.InlineKeyboardMarkup()
for i in message.text.split('\n'):
buttons = i.split(',')
buttons = [j.split(';') for j in buttons]
args = [types.InlineKeyboardButton(j[0].strip(), j[1].strip()) for j in buttons]
keyboard.row(*args)
bot.send_message(user, 'Кнопки будут выглядеть вот так:', reply_markup=keyboard)
bot.send_message(user, 'Теперь введите дату в виде часы - минуты - день - месяц (необязательно) - '
'год (необязательно), или введите now, чтобы выпустить сейчас:')
new_post.append(keyboard)
action = 'data'
elif action == 'data':
t = message.text.split('-')
if len(t) == 5:
t = [int(i) for i in t]
date = datetime(minute=t[1], hour=t[0], day=t[2], month=t[3], year=t[4])
elif len(t) == 4:
t = [int(i) for i in t]
date = datetime(minute=t[1], hour=t[0], day=t[2], month=t[3], year=datetime.now().year)
elif len(t) == 3:
t = [int(i) for i in t]
date = datetime(minute=t[1], hour=t[0], day=t[2], month=datetime.now().month, year=datetime.now().year)
else:
date = 'Now!'
new_post.append(date)
inkb = types.InlineKeyboardMarkup()
inkb.row(types.InlineKeyboardButton('Создать', callback_data='create'))
inkb.row(types.InlineKeyboardButton('Нет!', callback_data='delete'))
bot.send_message(user, 'Подтвердите создание отложенной записи:\n\n'
f'Текст: {new_post[0]}\n'
f'Дата: {str(new_post[2])}', reply_markup=inkb, parse_mode='Markdown')
@bot.callback_query_handler(func=lambda call: True)
def answer(call):
global new_post, action
us = call.message.chat.id
if call.data == 'create':
identity = datetime.now().microsecond
if type(new_post[2]) == str:
bot.send_message(channel, new_post[0], reply_markup=new_post[1], parse_mode='Markdown')
return
inkb = types.InlineKeyboardMarkup()
bot.send_message(us, 'Сообщение создано!', reply_markup=inkb)
posts[identity] = Thread(target=sleep_poster, args=[new_post[2], [channel, new_post[0], new_post[1], new_post[3]]])
posts[identity].run()
elif call.data == 'delete':
new_post = []
action = ''
bot.send_message(us, 'Создание отменено.')
def main():
while True:
try:
bot.polling()
except Exception as e:
print(e)
Thr = Thread(target=main)
Thr.start()
import asyncio
from telegram import Bot
# Укажите здесь ваш токен бота Telegram
bot_token = 'ВАШ_ТОКЕН'
# Укажите здесь идентификатор целевой группы, куда нужно отправлять сообщения
group_id = 'ВАШ_ИДЕНТИФИКАТОР_ГРУППЫ'
# Текст сообщения
message_text = 'Привет всем участникам группы!'
async def send_message_to_group_members():
# Создание экземпляра бота
bot = Bot(token=bot_token)
# Получение списка участников группы
group_members = await bot.get_chat_members_count(chat_id=group_id)
# Отправка сообщения каждому участнику группы
for member in group_members:
user_id = member.user.id
try:
await bot.send_message(chat_id=user_id, text=message_text)
print(f'Сообщение отправлено пользователю с ID {user_id}')
except Exception as e:
print(f'Ошибка при отправке сообщения пользователю с ID {user_id}: {e}')
# Отправка сообщения в группу от вашего бота
await bot.send_message(chat_id=group_id, text=message_text)
print('Сообщение отправлено в группу')
# Запуск асинхронной функции
asyncio.run(send_message_to_group_members())
if message.text == 'Писар':
user_info = db.get_gender_chat('male')
chat_two = user_info[0]
if db.get_vip(message.chat.id) == '250':
if db.create_chat(message.chat.id, chat_two) == False:
db.add_queue(message.chat.id, db.get_gender(message.chat.id))
bot.send_message(message.chat.id, 'Дар ҳоли ҷустуҷӯ, интизор шавед бо нафаре пайваст мешавед!', reply_markup=stop_search())
else:
mess = 'Нафаре ёфт шуд ки бо шумо дар алоқа аст суҳбатро оғоз намоед\nБарои қатъи сӯҳбат /stop - ро пахш намоед!'
bot.send_message(message.chat.id, mess, reply_markup=stop_dialog())
bot.send_message(chat_two, mess, reply_markup=stop_dialog())
else:
bot.send_message(message.chat.id, 'Ошибка: Вип не равен 250')
from telethon.sync import TelegramClient
api_id = 'YOUR_API_ID'
api_hash = 'YOUR_API_HASH'
phone_number = 'YOUR_PHONE_NUMBER'
with TelegramClient('session_name', api_id, api_hash) as client:
client.connect()
if not client.is_user_authorized():
client.send_code_request(phone_number)
client.sign_in(phone_number, input('Enter the code: '))
dialogs = client.get_dialogs()
for dialog in dialogs:
client.delete_dialog(dialog.id)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float camSens = 0.25f;
private Vector3 lastMouse = Vector3.zero;
private Rigidbody rb;
public float speed = 6.0f;
void Awake()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
Vector3 mouseDelta = Input.mousePosition - lastMouse;
float mouseX = mouseDelta.x * camSens;
float mouseY = -mouseDelta.y * camSens;
lastMouse = Input.mousePosition;
Vector3 currentRotation = transform.rotation.eulerAngles;
currentRotation.y += mouseX;
transform.rotation = Quaternion.Euler(currentRotation);
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
Vector3 moveDirection = new Vector3(horizontalInput, 0, verticalInput).normalized;
moveDirection = transform.TransformDirection(moveDirection);
Vector3 newPosition = rb.position + moveDirection * speed * Time.deltaTime;
rb.MovePosition(newPosition);
if (Input.GetKey("space"))
{
transform.position = Vector3.zero;
}
}
}
//2nd way to get object from array
function findByName(jsonData) {
for(let item of jsonData) {
if(item.title == pm.collectionVariables.get("schoolTitle")) {
return item;
}
}
}
console.log(findByName(jsonData));
var itemData = findByName(jsonData);
pm.environment.set("2ndId", itemData.id);
//2nd way to get object Index from array
function findObjectIndex(jsonData) {
for(const [index, item] of jsonData.entries()) {
if(item.title == pm.collectionVariables.get("schoolTitle")) {
return index;
}
}
}
console.log(findObjectIndex(jsonData));
var itemIndex = findObjectIndex(jsonData);
pm.environment.set("Index", itemIndex);
wait.until(EC.element_to_be_clickable(...
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC