Skip to content

Commit

Permalink
release
Browse files Browse the repository at this point in the history
  • Loading branch information
kondaurovDev committed Jan 22, 2025
1 parent 835cb36 commit 2d7a3d1
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ const makeRunnableBot = (tsTextModel, worker) => (state) => tsTextModel.getJsCod
console.warn("Serizalized js code not defined");
return;
}
console.log("code", code.serialized);
worker.postMessage({
command: "run-bot",
token: state.bot.token,
Expand All @@ -52,23 +53,29 @@ const makeRunnableBot = (tsTextModel, worker) => (state) => tsTextModel.getJsCod
});
const checkTokenAndRun = (state, runnableBot) => {
const token = state.bot.token;
if (!token) return;
if (!token) {
state.bot.isReachable = false;
return;
}
fetch(`https://api.telegram.org/bot${token}/getMe`).then((_) => _.json()).then((info) => {
if (info.ok) {
state.bot.name = info.result.first_name;
state.bot.isReachable = true;
console.log("Running bot");
runnableBot(state);
} else {
state.bot.name = "nameless";
state.bot.isReachable = false;
}
}).catch((error2) => {
console.warn("check token error", error2);
state.bot.isReachable = false;
});
};
const makeBotLauncher = async (tsTextModel) => {
const worker = new Worker(new URL(
/* @vite-ignore */
"" + new URL("web-worker-CgNZSpPE.js", import.meta.url).href,
"" + new URL("web-worker-Cdzbvpxg.js", import.meta.url).href,
import.meta.url
), { type: "module" });
if (!worker) return;
Expand Down Expand Up @@ -179,15 +186,12 @@ const __vitePreload = function preload(baseModule, deps, importerUrl) {
const makeTsTextModel = async (monaco) => {
const emptyExample = await fetchText("./example/empty.ts");
const tsModel = monaco.editor.createModel(emptyExample, "typescript");
let cachedWorkerPromise = null;
let tsWorker = null;
const getTsCode = async () => {
if (!cachedWorkerPromise) {
cachedWorkerPromise = (async () => {
const tsWorker = await monaco.languages.typescript.getTypeScriptWorker();
return tsWorker(tsModel.uri);
})();
if (!tsWorker) {
tsWorker = await monaco.languages.typescript.getTypeScriptWorker().then((_) => _(tsModel.uri));
}
return cachedWorkerPromise.then((_) => _.getEmitOutput(tsModel.uri.toString()));
return tsWorker.getEmitOutput(tsModel.uri.toString());
};
return {
tsModel,
Expand Down Expand Up @@ -3557,7 +3561,9 @@ const makeGlobalState = (alpine) => {
bot: {
name: "nameless",
status: "idle",
token: ""
token: "",
isAutoReload: false,
isReachable: false
},
selectedExample: "empty.ts",
botUpdates: []
Expand All @@ -3574,7 +3580,11 @@ async function setup() {
if (!editor) return;
const botLauncher = await makeBotLauncher(editor.tsTextModel);
if (!botLauncher) return;
editor.onCodeChange(() => {
editor.onCodeChange(async () => {
if (!state.bot.isReachable || !state.bot.isAutoReload) return;
botLauncher.runBot(state);
});
document.addEventListener("reload-bot", () => {
botLauncher.runBot(state);
});
document.addEventListener("check-token", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -872,7 +872,6 @@ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "
}
}
const causeInterrupt = (traces = []) => new Interrupt(traces);
const causeIsFail = (self2) => self2._tag === "Fail";
const causeIsInterrupt = (self2) => self2._tag === "Interrupt";
const MicroFiberTypeId = /* @__PURE__ */ Symbol.for("effect/Micro/MicroFiber");
const fiberVariance = {
Expand Down Expand Up @@ -1340,22 +1339,6 @@ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "
...options,
while: (exit2) => exit2._tag === "Success" && ((options == null ? void 0 : options.while) === void 0 || options.while(exit2.value))
}));
const catchAllCause = /* @__PURE__ */ dual(2, (self2, f) => {
const onFailure = Object.create(OnFailureProto);
onFailure[args] = self2;
onFailure[failureCont] = f;
return onFailure;
});
const OnFailureProto = /* @__PURE__ */ makePrimitiveProto({
op: "OnFailure",
eval(fiber) {
fiber._stack.push(this);
return this[args];
}
});
const catchCauseIf = /* @__PURE__ */ dual(3, (self2, predicate, f) => catchAllCause(self2, (cause) => predicate(cause) ? f(cause) : failCause$1(cause)));
const tapErrorCauseIf = /* @__PURE__ */ dual(3, (self2, refinement, f) => catchCauseIf(self2, refinement, (cause) => andThen(f(cause), failCause$1(cause))));
const tapError = /* @__PURE__ */ dual(2, (self2, f) => tapErrorCauseIf(self2, causeIsFail, (fail2) => f(fail2.error)));
const matchCauseEffect = /* @__PURE__ */ dual(2, (self2, options) => {
const primitive = Object.create(OnSuccessAndFailureProto);
primitive[args] = self2;
Expand Down Expand Up @@ -2971,6 +2954,8 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
Base.prototype.name = tag;
return Base;
};
var BotMessageHandler = class extends Tag("BotMessageHandler")() {
};
var makeSettingsFrom = (input) => {
let limit = input.batch_size ?? 10;
let timeout = input.timeout ?? 10;
Expand Down Expand Up @@ -3192,24 +3177,23 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
})
);
};
var BotUpdatePollerService = class extends Tag("BotUpdatePollerService")() {
};
(class extends Tag("BotUpdatePollerService")() {
});
var BotUpdatesPollerServiceDefault = gen(function* () {
console.log("Initiating BotUpdatesPollerServiceDefault");
const state = {
fiber: void 0
};
const runBot = (messageHandler) => gen(function* () {
const runBot = gen(function* () {
console.log("run bot");
const messageHandler = yield* service(BotMessageHandler);
const startFiber = pollAndHandle({
settings: messageHandler
}).pipe(
forkDaemon,
tap(
(fiber) => fiber.addObserver((exit2) => {
console.log("bot's fiber has been closed", exit2);
if (messageHandler.onExit) {
messageHandler.onExit(exit2);
}
})
)
);
Expand All @@ -3219,10 +3203,10 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
}
state.fiber = yield* startFiber;
console.log("Fetching bot updates via long polling...");
return state.fiber;
});
return {
runBot
runBot,
getFiber: () => state.fiber
};
});
var makeClientConfigFrom = (input) => gen(function* () {
Expand All @@ -3246,43 +3230,33 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
}
return makeTgBotClientConfig(config);
});
var makeBot = (messageHandler) => gen(function* () {
const { runBot } = yield* service(BotUpdatePollerService);
const fiber = yield* runBot(messageHandler);
const interrupt = fiberInterrupt(fiber);
return {
runBot,
interrupt
};
}).pipe(
tapError((error) => {
console.error(error);
return void_;
})
);
(class extends Tag("BotFactoryService")() {
});
var BotFactoryServiceDefault = {
makeBot,
runBot: (input) => gen(function* () {
const client = make$2(TgBotClientConfig, yield* makeClientConfigFrom(input));
const poller = yield* BotUpdatesPollerServiceDefault.pipe(
provideContext(client)
);
const bot = yield* makeBot(input).pipe(
provideContext(client),
provideService(BotUpdatePollerService, poller)
);
const reload = (input2) => bot.runBot(input2).pipe(
yield* poller.runBot.pipe(
provideService(BotMessageHandler, input),
provideContext(client)
);
const reload = (input2) => poller.runBot.pipe(
provideService(BotMessageHandler, input2),
provideContext(client),
runPromise
);
return {
reload,
bot
fiber: poller.getFiber
};
})
};
var runTgChatBot = (input) => BotFactoryServiceDefault.runBot(input).pipe(runPromise);
var runTgChatBot = (input) => BotFactoryServiceDefault.runBot(input).pipe(
provideService(BotMessageHandler, input),
runPromise
);
var getFile = (fileId) => gen(function* () {
const response = yield* execute("get_file", { file_id: fileId });
const config = yield* service(TgBotClientConfig);
Expand Down Expand Up @@ -3345,6 +3319,7 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
messageId: messageId++
});
return async (command) => {
var _a2;
if (!isRunBot(command)) {
sendEvent({
error: "not a run bot command",
Expand All @@ -3354,6 +3329,7 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
}
if (command.command == "run-bot") {
const handlers = deserialize(command.code);
console.log("worker got run-bot command", handlers);
if (botInstance) {
console.log("reloading...");
await botInstance.reload({
Expand All @@ -3369,14 +3345,16 @@ ${this.stack.split("\n").slice(1).join("\n")}` : this.toString();
botInstance = await runTgChatBot({
type: "config",
bot_token: command.token,
...handlers,
onExit: (exit2) => sendEvent({
...handlers
});
(_a2 = botInstance.fiber()) == null ? void 0 : _a2.addObserver((exit2) => {
sendEvent({
success: "Bot's fiber has been shutdown",
exit: exit2,
botState: {
status: "stopped"
}
})
});
});
sendEvent({
success: "Bot's fiber has been created",
Expand Down
15 changes: 14 additions & 1 deletion docs/tg-bot-playground/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<script defer src="https://cdn.jsdelivr.net/npm/@monaco-editor/[email protected]/lib/umd/monaco-loader.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha512-Evv84Mr4kqVGRNSgIGL/F/aIDqQb7xQ2vcrdIwxfjThSH8CSR7PBEakCr51Ck+w+/U6swU2Im1vVX0SVk9ABhg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="icon" type="image/png" sizes="32x32" href="./favicon.ico">


<script type="module" crossorigin src="./assets/index-ChPUFYFo.js"></script>
<script type="module" crossorigin src="./assets/index-BFvUFyQr.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-Grbd-L5t.css">
</head>

Expand All @@ -18,6 +19,18 @@ <h2>Telegram Bot Playground 🤖 </h2>

<div style="display: flex; gap: 20px; justify-content: center;">

<label x-show="$store.state.bot.isReachable">
Auto-Reload
<input
type="checkbox"
x-model="$store.state.bot.isAutoReload"
>
</label>

<button type="button" @click="$dispatch('reload-bot')">
<i class="fas fa-refresh"></i>
</button>

<label>
Bot token
<input type="text" x-model="$store.state.bot.token" placeholder="your token"
Expand Down

0 comments on commit 2d7a3d1

Please sign in to comment.