Форум сайта python.su
[code python]
import requests
import telebot
# Укажите токен вашего бота
TOKEN = 'your_bot_token_here'
# Создаем экземпляр бота
bot = telebot.TeleBot(TOKEN)
# Обработчик команды /start
@bot.message_handler(commands=['start'])
def send_welcome(message):
bot.reply_to(message, "Привет! Введите команду /exchange, чтобы получить актуальные курсы валют.")
# Обработчик команды /exchange
@bot.message_handler(commands=['exchange'])
def send_exchange(message):
url = 'https://www.primbank.ru/local/cron/infoVl.php?idType=4&idCity=1'
response = requests.get(url)
if response.status_code == 200:
data = response.json()
# Отправляем сообщение с актуальными курсами валют
bot.reply_to(message, f"Курс USD: {data['USD']['buy']} / {data['USD']['sell']}\nКурс EUR: {data['EUR']['buy']} / {data['EUR']['sell']}")
else:
bot.reply_to(message, "Произошла ошибка при получении курсов валют.")
# Запускаем бота
bot.polling()
[/code]
def table(self): # создание таблицы self.table = QtWidgets.QTableWidget(self.centralwidget) self.table.setGeometry(QtCore.QRect(10, 50, 462, 950)) self.table.setStyleSheet("background-color:rgb(209, 209, 209)") self.headerLabels = list('A') n = 3000 self.table.setRowCount(n) self.table.setColumnCount(len(self.headerLabels)) self.table.setHorizontalHeaderLabels(self.headerLabels) self.table.horizontalHeader().setDefaultSectionSize(100) self.table.horizontalHeader().setMinimumSectionSize(125) self.table.verticalHeader().setVisible(False) self.table.verticalHeader().setDefaultSectionSize(25) self.table.verticalHeader().setMinimumSectionSize(25) for row in range(n): for col in range(len(self.headerLabels)): item = QTableWidgetItem(''.format(self.headerLabels[col], row)) self.table.setItem(row, col, item) self.table.resizeColumnsToContents() self.table.resizeRowsToContents()
class GraphicsView(QGraphicsView): # +++ clicked = pyqtSignal(str, str) def mousePressEvent(self, event): super(GraphicsView, self).mousePressEvent(event) self.setCursor(Qt.DragMoveCursor) # Получить положение мыши на экране pos = event.globalPos() image = QApplication.primaryScreen().grabWindow( int(QApplication.desktop().winId()), pos.x() - 23, pos.y() - 23, 47, 47).toImage() color = image.pixelColor(23, 23) if color.isValid(): self.clicked.emit('View', color.name()) def mouseReleaseEvent(self, event): super(GraphicsView, self).mouseReleaseEvent(event) self.setCursor(Qt.ArrowCursor)
class MainssWindow(QMainWindow, Ui_MainsWindow): def __init__(self): super().__init__() self.setupUi(self) self.layout = QtWidgets.QHBoxLayout(self.wid) self.layout.addWidget(self.wid) self.scene = GraphicsScene() self.scene.setSceneRect(0, 0, 1400, 900) width = Settings.NUM_BLOCKS_X * Settings.WIDTH height = Settings.NUM_BLOCKS_Y * Settings.HEIGHT self.scene.setSceneRect(0, 0, width, height) self.scene.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex) self.setMouseTracking(True) self.graphicsView.setScene(self.scene) self.scene.clicked.connect(self.point1) self.graphicsView.clicked.connect(self.point1) # +++ self.table()
class QS(QtWidgets.QGraphicsScene): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) width = Settings.NUM_BLOCKS_X * Settings.WIDTH height = Settings.NUM_BLOCKS_Y * Settings.HEIGHT self.setSceneRect(0, 0, width, height) self.setItemIndexMethod(QtWidgets.QGraphicsScene.NoIndex) for x in range(0,Settings.NUM_BLOCKS_X+1): xc = x * Settings.WIDTH self.addLine(xc,0,xc,height) for y in range(0,Settings.NUM_BLOCKS_Y+1): yc = y * Settings.HEIGHT self.addLine(0,yc,width,yc)
class GraphicsScene(QGraphicsScene): clicked = pyqtSignal(str, QPointF) def mousePressEvent(self, event): super(GraphicsScene, self).mousePressEvent(event) sp = event.scenePos() self.clicked.emit('Scene', sp)
def point1(self, text, value): if text == 'Scene': self.lab.setText(f'x1 = {value.x()}, y1 = {value.y()}. Интенсивность: ') if text == 'View': self.lab.setText(f'{self.lab.text()} {value}')
import sys from pathlib import Path from PyQt5.QtWidgets import * app = QApplication(sys.argv) win = QWidget() win.setGeometry(1400, 1400, 1400, 1300) layout = QGridLayout() for i in range(5): for j in range(5): label = QLabel('plist_down.py') button1 = QPushButton('Open (E:\__Moi_scripti\03_yotube_plist_downloader)') button2 = QPushButton('Run Script') layout.addWidget(label, i, j) layout.addWidget(button1, i, j+1) layout.addWidget(button2, i, j+2) win.setLayout(layout) win.show() sys.exit(app.exec_())
import discord import os from discord.ext import commands from dotenv import load_dotenv import whisper from tts import tts from parse_statement import parse load_dotenv() intents = discord.Intents.all() client = commands.Bot(command_prefix="&", intents=intents) # model = whisper.load_model("base") model = whisper.load_model("small") # join vc @client.command() async def join(ctx): if ctx.author.voice: channel = ctx.message.author.voice.channel await channel.connect() else: await ctx.send("not in a voice channel!") # leave vc @client.command() async def leave(ctx): if ctx.voice_client: await ctx.voice_client.disconnect() else: await ctx.send("not in a voice channel!") # play tts audio from command @client.command() async def play(ctx, *, arg): tts(ctx, arg) @client.command() async def listen(ctx): if ctx.voice_client: ctx.voice_client.start_recording(discord.sinks.WaveSink(), callback, ctx) await ctx.send("listening...") else: await ctx.send("not in a voice channel!") async def callback(sink: discord.sinks, ctx): for user_id, audio in sink.audio_data.items(): if user_id == ctx.author.id: audio: discord.sinks.core.AudioData = audio print(user_id) filename = "audio.wav" with open(filename, "wb") as f: f.write(audio.file.getvalue()) text = model.transcribe(filename)["text"] os.remove(filename) print(f"Received from {ctx.author.name}: {text}") reply = parse(text) print(f"Reply: {reply}") tts(ctx, reply) # stops recording @client.command() async def stop(ctx): ctx.voice_client.stop_recording() @client.event async def on_ready(): print(f"We have logged in as {client.user}") @client.event async def on_message(message): await client.process_commands(message) if message.author == client.user: return # ping if message.content.startswith("ping"): await message.channel.send("pong") client.run(os.environ.get("DISCORD"))
(discord) PS D:\discord> & CUsers/Gena/.virtualenvs/discord-q4ERoUCO/Scripts/python.exe d
discord/package/test/bot.py
Traceback (most recent call last):
File “d:\discord\package\test\bot.py”, line 7, in <module>
import whisper
File “C:\Users\Gena\.virtualenvs\discord-q4ERoUCO\lib\site-packages\whisper.py”, line 69, in <module>
libc = ctypes.CDLL(libc_name)
File “C:\Users\Gena\AppData\Local\Programs\Python\Python310\lib\ctypes\__init__.py”, line 364, in __init__
if ‘/’ in name or ‘\\’ in name:
TypeError: argument of type ‘NoneType’ is not iterable
(discord) PS D:\discord>
import calendar import datetime def get_birthdays_per_week(users): # get the current day now = datetime.datetime.now() # get the day of the week, 0-monday, 1-tuesday day_num = now.weekday() # create a dictionary to store the list of users per day birthdays_by_day = dict() # iterate over the users list for user in users: # calculate the difference in days between the current day and the user's birthday difference_in_days = (user['birthday'] - now).days # check if the difference is between 0 and 7 if 0 <= difference_in_days <= 7: # get the day number of the user's birthday user_day_num = (user['birthday'].weekday() - day_num) % 7 # extract the name of the user user_name = user['name'] # get the list of users for the user's birthday day user_list = birthdays_by_day.get(user_day_num, []) # add the name of the user to the list of users on the user's birthday day user_list.append(user_name) # update the dictionary birthdays_by_day[user_day_num] = user_list # loop over days for day_num, user_list in birthdays_by_day.items(): # get the day name day_name = calendar.day_name[day_num] # format and print users print('{}: {}'.format(day_name, ', '.join(user_list)))
Exception in thread Thread-2988: Exception in thread Thread-2987: Traceback (most recent call last): Traceback (most recent call last): File "C:\Users\Gena\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner File "C:\Users\Gena\.virtualenvs\discord-q4ERoUCO\lib\site-packages\mysql\connector\cursor_cext.py", line 279, in execute self.run() File "C:\Users\Gena\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1378, in run result = self._cnx.cmd_query( File "C:\Users\Gena\.virtualenvs\discord-q4ERoUCO\lib\site-packages\mysql\connector\connection_cext.py", line 587, in cmd_query self.function(*self.args, **self.kwargs) return self.fetch_eof_status() File "D:\discord\package\time\timelocal.py", line 45, in timenows File "C:\Users\Gena\.virtualenvs\discord-q4ERoUCO\lib\site-packages\mysql\connector\connection_cext.py", line 510, in fetch_eof_status showdostime = package.setup.getsettings.timeingshowindows() "insert_id": self._cmysql.insert_id(), File "D:\discord\package\setup\getsettings.py", line 115, in timeingshowindows _mysql_connector.MySQLInterfaceError: Lost connection to MySQL server during query selectsettingfromdatabase() The above exception was the direct cause of the following exception: File "D:\discord\package\setup\getsettings.py", line 25, in selectsettingfromdatabase Traceback (most recent call last): mycursor = myconnect.cursor(buffered=False) File "C:\Users\Gena\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner File "C:\Users\Gena\.virtualenvs\discord-q4ERoUCO\lib\site-packages\mysql\connector\connection_cext.py", line 632, in cursor self.run() raise OperationalError("MySQL Connection not available.") File "C:\Users\Gena\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1378, in run mysql.connector.errors.OperationalError: MySQL Connection not available.
from django.shortcuts import render
from django.contrib.auth.models import User
from django.views.generic import DetailView
from register.models import UserCoin
def index2(request):
username = User.objects.all()
usercoin = UserCoin.objects.all()
return render(request, 'main2/index2.html', {"username": username, "usercoin": usercoin})
class Users(DetailView):
model = User
template_name = 'index2.html'
context_object_name = 'user'
class Coins(DetailView):
model = UserCoin
template_name = 'index2.html'
context_object_name = 'coin'
from django.db import models
from django.contrib.auth.models import User
class UserCoin(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
coin = models.DecimalField(null=False, decimal_places=2, max_digits=1000, default=1)
def __str__(self):
return f'{self.coin}'
sem = threading.Semaphore(S_THREADS) thr_lst = [] for ind, mail_to in enumerate(mail_list): if ind > 0 and ind % int(S_COUNTER_OF_SENT_EMAILS) == 0: send_for_my_email() print(f'Pause time = {S_PAUSE_TIME} sec') time.sleep(S_PAUSE_TIME) thr = threading.Thread( target=run_smtp_send_with_semaphore, args=(mail_to, sem), daemon=True ) thr_lst.append(thr) thr.start() [i_thr.join() for i_thr in thr_lst]
thr_lst = [] sem = threading.Semaphore(S_THREADS) with sem: for ind, mail_to in enumerate(mail_list): if (ind != 0) and (ind % int(S_COUNTER_OF_SENT_EMAILS)) == 0: send_for_my_email() thr = threading.Thread( target=run_smtp_send, args=(mail_to,), daemon=True ) thr_lst.append(thr) thr.start() [i_thr.join() for i_thr in thr_lst]
import telebot from telebot import types token = '!!!!!!!!!!!!!!!!!!!!!!' bot = telebot.TeleBot(token) channel_brn = '' # id канала channel_omsk = '' # id канала txt = 'Текст' @bot.message_handler(commands=['start']) def start(message): markup = types.ReplyKeyboardMarkup(resize_keyboard = True) item1 = types.KeyboardButton('Разместить объявление') item2 = types.KeyboardButton('Правила') markup.add(item1, item2) bot.send_message(message.chat.id, txt.format(message.from_user), reply_markup=markup) @bot.message_handler(content_types=['text']) def bot_message(message): if message.text == 'Выберите город': markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton('Город 1') item2 = types.KeyboardButton('Город 2') back = types.KeyboardButton ('<-- Назад') markup.add(item1, item2, back) bot.send_message(message.chat.id, 'Выберите город', reply_markup=markup) elif message.text == 'Город 1': bot.send_message(message.chat.id, 'Введите текст Вашего объявления для Город 1', parse_mode='html') bot.send_message(chat_id=channel_brn, text='example') elif message.text == 'Правила': markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton('Правила 1') item2 = types.KeyboardButton('Правила 2') back = types.KeyboardButton ('<-- Назад') markup.add(item1, item2, back) bot.send_message(message.chat.id, 'Правила', reply_markup=markup) elif message.text == '<-- Назад': markup = types.ReplyKeyboardMarkup(resize_keyboard=True) item1 = types.KeyboardButton('Разместить объявление') item2 = types.KeyboardButton('Правила') markup.add(item1, item2) bot.send_message(message.chat.id, '<-- Назад', reply_markup=markup) bot.polling(none_stop=True)
import pygame as pg pg.init() w = 1000 h = 600 FPS = 60 clock = pg.time.Clock() win = pg.display.set_mode((w,h)) tank_player = [pg.image.load('Hull_02_A.png'),pg.image.load('Hull_02_B.png')] angle = 0 anim_count = 0 def tank(): global anim_count clock.tick(8) key = pg.key.get_pressed() if key[pg.K_w]: if anim_count == 0: anim_count = 1 else: anim_count = 0 a = pg.transform.rotate(tank_player[0], angle) #Вот отрисовка объекта win.blit(tank_player[anim_count],(0, 0)) pg.display.update() run = True while run: for event in pg.event.get(): if event.type == pg.QUIT: run = False tank() pg.display.flip()