Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/?q=discord&page=1&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=discord

Returns an array of strings in format "username" or "username/projectName"

Found 664 results for "discord"(457ms)

my-first-valREADME.md1 match

@ktreilly•Updated 7 hours ago
9Feel free to edit these examples or add new files to your project.
10
11For inspiration, check out our [Docs](https://docs.val.town/), [Templates](https://www.val.town/explore/use-cases), [Showcase](https://www.val.town/explore/community-showcase) and [Discord](https://discord.val.town/)!
12
13Stay as long as you'd like in this project, or head to your main [dashboard](/dashboard) to keep exploring the rest of Val Town.

tanstackReactHonoExampleREADME.md1 match

@sistrall•Updated 11 hours ago
12This "migration" runs once on every app startup because it's imported in `index.ts`. You can comment this line out for a slight (30ms) performance improvement on cold starts. It's left in so that users who fork this project will have the migration run correctly.
13
14SQLite has much more limited support for altering existing tables as compared to other databases. Often it's easier to create new tables with the schema you want, and then copy the data over. Happily LLMs are quite good at those sort of database operations, but please reach out in the [Val Town Discord](https://discord.com/invite/dHv45uN5RY) if you need help.
15
16## Queries

reactHonoExampleREADME.md1 match

@newenquiry•Updated 1 day ago
24want, and then copy the data over. Happily LLMs are quite good at those sort of
25database operations, but please reach out in the
26[Val Town Discord](https://discord.com/invite/dHv45uN5RY) if you need help.
27
28## Queries

portfolio-trackermain.ts3 matches

@dm_antoine•Updated 1 day ago
13 }
14
15 const discordUrl = Deno.env.get("DISCORD_URL")!;
16
17 let body: any = {};
42
43 if (isLeaving) {
44 await fetch(discordUrl, {
45 method: "POST",
46 headers: { "Content-Type": "application/json" },
66 });
67 } else {
68 await fetch(discordUrl, {
69 method: "POST",
70 headers: { "Content-Type": "application/json" },

catnipdiscord-api_test.ts25 matches

@catalloc•Updated 2 days ago
1import "../test/_mocks/env.ts";
2import { assertEquals, assert } from "../test/assert.ts";
3import { commandsPath, discordBotFetch, remainingMs, _internals } from "./discord-api.ts";
4import { mockFetch, getCalls, restoreFetch, setNextThrow } from "../test/_mocks/fetch.ts";
5
20});
21
22Deno.test("discordBotFetch: retries on 429 and succeeds", async () => {
23 mockFetch({
24 responses: [
28 });
29 try {
30 const result = await discordBotFetch("GET", "test");
31 assertEquals(result.ok, true);
32 assertEquals(result.data?.id, "msg1");
37});
38
39Deno.test("discordBotFetch: retries on 5xx and succeeds", async () => {
40 mockFetch({
41 responses: [
45 });
46 try {
47 const result = await discordBotFetch("POST", "channels/1/messages", { content: "hi" });
48 assertEquals(result.ok, true);
49 assertEquals(getCalls().length, 2);
53});
54
55Deno.test("discordBotFetch: does not retry on 4xx", async () => {
56 mockFetch({
57 responses: [
60 });
61 try {
62 const result = await discordBotFetch("GET", "test");
63 assertEquals(result.ok, false);
64 assertEquals(result.status, 403);
69});
70
71Deno.test("discordBotFetch: retries on network error and succeeds", async () => {
72 mockFetch({
73 responses: [
77 setNextThrow(new Error("network down"));
78 try {
79 const result = await discordBotFetch("GET", "test");
80 assertEquals(result.ok, true);
81 assertEquals(result.data?.recovered, true);
88// --- 204 No Content ---
89
90Deno.test("discordBotFetch: 204 No Content returns ok with no data", async () => {
91 mockFetch({
92 responses: [
95 });
96 try {
97 const result = await discordBotFetch("DELETE", "channels/1/messages/2");
98 assertEquals(result.ok, true);
99 assertEquals(result.status, 204);
106// --- undefined body omits Content-Type ---
107
108Deno.test("discordBotFetch: undefined body omits Content-Type header", async () => {
109 mockFetch({ default: { status: 200, body: { ok: true } } });
110 try {
111 await discordBotFetch("GET", "test");
112 const call = getCalls()[0];
113 const headers = call.init?.headers as Record<string, string> | undefined;
120});
121
122Deno.test("discordBotFetch: body provided includes Content-Type header", async () => {
123 mockFetch({ default: { status: 200, body: { ok: true } } });
124 try {
125 await discordBotFetch("POST", "test", { content: "hi" });
126 const call = getCalls()[0];
127 const headers = call.init?.headers as Record<string, string> | undefined;
150// --- network error exhausts retries ---
151
152Deno.test("discordBotFetch: persistent network error returns error after retries", async () => {
153 mockFetch({ default: { status: 200, body: {} } });
154 setNextThrow(new Error("first fail"));
155 try {
156 // First call throws (network error), retry succeeds
157 const result = await discordBotFetch("GET", "test");
158 assertEquals(result.ok, true);
159 } finally {
175});
176
177Deno.test("discordBotFetch: 429 rejected when time budget insufficient", async () => {
178 // Set isolate start far in the past so remainingMs is very small
179 _internals.setIsolateStart(Date.now() - 9.5 * 60 * 1000 + 5000); // ~5s left
184 });
185 try {
186 const result = await discordBotFetch("GET", "test");
187 assertEquals(result.ok, false);
188 assertEquals(result.status, 429);
195});
196
197Deno.test("discordBotFetch: 5xx not retried when time budget insufficient", async () => {
198 _internals.setIsolateStart(Date.now() - 9.5 * 60 * 1000 + 10000); // ~10s left, < 32s threshold
199 mockFetch({
203 });
204 try {
205 const result = await discordBotFetch("GET", "test");
206 assertEquals(result.ok, false);
207 assertEquals(result.status, 500);
213});
214
215Deno.test("discordBotFetch: network error not retried when time budget insufficient", async () => {
216 _internals.setIsolateStart(Date.now() - 9.5 * 60 * 1000 + 10000); // ~10s left
217 mockFetch({ default: { status: 200, body: {} } });
218 setNextThrow(new Error("network down"));
219 try {
220 const result = await discordBotFetch("GET", "test");
221 assertEquals(result.ok, false);
222 assertEquals(result.status, 0);
229});
230
231Deno.test("discordBotFetch: max retries returns error after 2 attempts", async () => {
232 _internals.resetIsolateStart(); // plenty of time
233 mockFetch({
238 });
239 try {
240 const result = await discordBotFetch("GET", "test");
241 assertEquals(result.ok, false);
242 assertEquals(result.status, 500);

catnipdiscord-api.ts8 matches

@catalloc•Updated 2 days ago
1/**
2 * discord/discord-api.ts
3 *
4 * Shared helper for Discord Bot API calls.
5 * Centralizes URL construction, Bot auth headers, and error handling.
6 */
19}
20
21export interface DiscordApiResult {
22 ok: boolean;
23 status: number;
27
28/**
29 * Make an authenticated request to the Discord Bot API.
30 * Builds the full URL, attaches Bot token, and handles response parsing.
31 */
32/**
33 * Build the Discord API path for application commands.
34 */
35export function commandsPath(appId: string, guildId?: string, commandId?: string): string {
44}
45
46export async function discordBotFetch(
47 method: string,
48 path: string,
49 body?: unknown,
50): Promise<DiscordApiResult> {
51 const headers: Record<string, string> = {
52 Authorization: `Bot ${CONFIG.botToken}`,
60 for (let attempt = 0; attempt < 2; attempt++) {
61 try {
62 const response = await fetch(`https://discord.com/api/v10/${path}`, {
63 method,
64 headers,

catnipsend_test.ts28 matches

@catalloc•Updated 2 days ago
3import { _internals, send } from "./send.ts";
4
5const { truncateText, splitMessage, calculateEmbedSize, sanitizeEmbed, chunkEmbeds, DISCORD_LIMITS } = _internals;
6
7// --- truncateText ---
36 assert(chunks.length > 1);
37 for (const chunk of chunks) {
38 assert(chunk.length <= DISCORD_LIMITS.contentLength);
39 }
40 assertEquals(chunks.join(""), msg);
55 assert(chunks.length >= 2);
56 for (const chunk of chunks) {
57 assert(chunk.length <= DISCORD_LIMITS.contentLength);
58 }
59 assertEquals(chunks.join(""), msg);
86Deno.test("sanitizeEmbed: truncates long title", () => {
87 const result = sanitizeEmbed({ title: "a".repeat(300) });
88 assert(result.title!.length <= DISCORD_LIMITS.title);
89});
90
91Deno.test("sanitizeEmbed: truncates long description", () => {
92 const result = sanitizeEmbed({ description: "a".repeat(5000) });
93 assert(result.description!.length <= DISCORD_LIMITS.description);
94});
95
111 footer: { text: "f".repeat(3000) },
112 });
113 assert(result.author!.name.length <= DISCORD_LIMITS.authorName);
114 assert(result.footer!.text.length <= DISCORD_LIMITS.footerText);
115});
116
151 for (const chunk of result) {
152 const totalSize = chunk.reduce((sum, e) => sum + calculateEmbedSize(e), 0);
153 assert(totalSize <= DISCORD_LIMITS.totalCharacters);
154 }
155});
161 globalThis.fetch = () => Promise.resolve(new Response(JSON.stringify({ id: "1" }), { status: 200 }));
162 try {
163 const result = await send("short message", "https://discord.com/api/webhooks/test/token");
164 assertEquals(result.success, true);
165 assertEquals(result.partialFailure, false);
176 // Message long enough to split into multiple chunks
177 const longMsg = "x".repeat(4500);
178 const result = await send(longMsg, "https://discord.com/api/webhooks/test/token");
179 assertEquals(result.success, true);
180 assertEquals(result.partialFailure, false);
192 callCount++;
193 // First two calls succeed (initial send + rate limit retry = 2 per chunk, but we have 1 success)
194 // Actually sendWithFallback calls sendToDiscordApi which has its own retry loop
195 // First chunk succeeds, second chunk fails
196 if (callCount <= 1) {
201 try {
202 const longMsg = "x".repeat(4500); // splits into 3 chunks
203 const result = await send(longMsg, "https://discord.com/api/webhooks/test/token");
204 assertEquals(result.success, true);
205 assertEquals(result.partialFailure, true);
216 globalThis.fetch = () => Promise.resolve(new Response("Bad Request", { status: 400 }));
217 try {
218 const result = await send("short message", "https://discord.com/api/webhooks/test/token");
219 assertEquals(result.success, false);
220 // partialFailure should be false (or undefined) when nothing succeeded
234 for (const chunk of result) {
235 const totalSize = chunk.reduce((sum, e) => sum + calculateEmbedSize(e), 0);
236 assert(totalSize <= DISCORD_LIMITS.totalCharacters, `Chunk exceeds ${DISCORD_LIMITS.totalCharacters} chars`);
237 }
238});
244 fields: [{ name: "x".repeat(300), value: "v".repeat(1500) }],
245 });
246 assert(result.fields![0].name.length <= DISCORD_LIMITS.fieldName);
247 assert(result.fields![0].value.length <= DISCORD_LIMITS.fieldValue);
248 assert(result.fields![0].name.endsWith("..."));
249 assert(result.fields![0].value.endsWith("..."));
256 globalThis.fetch = () => Promise.resolve(new Response(JSON.stringify({ id: "1" }), { status: 200 }));
257 try {
258 const result = await send({ title: "Test", description: "Hello" }, "https://discord.com/api/webhooks/test/token");
259 assertEquals(result.success, true);
260 assertEquals(result.sentDirectly, 1);
268Deno.test("send: no webhook URL returns error", async () => {
269 // Save and clear the config webhook
270 const origEnv = Deno.env.get("DISCORD_CONSOLE_WEBHOOK");
271 Deno.env.delete("DISCORD_CONSOLE_WEBHOOK");
272 try {
273 const result = await send("test", undefined);
275 assert(result.error?.includes("No webhook URL"));
276 } finally {
277 if (origEnv) Deno.env.set("DISCORD_CONSOLE_WEBHOOK", origEnv);
278 }
279});
282
283Deno.test("send: fallback webhook used on 4xx from primary", async () => {
284 const origEnv = Deno.env.get("DISCORD_CONSOLE");
285 Deno.env.set("DISCORD_CONSOLE", "https://discord.com/api/webhooks/fallback/token");
286 const originalFetch = globalThis.fetch;
287 let callCount = 0;
295 };
296 try {
297 const result = await send("test message", "https://discord.com/api/webhooks/primary/token");
298 assertEquals(result.success, true);
299 assertEquals(result.usedFallback, true);
300 } finally {
301 globalThis.fetch = originalFetch;
302 if (origEnv) Deno.env.set("DISCORD_CONSOLE", origEnv);
303 else Deno.env.delete("DISCORD_CONSOLE");
304 }
305});
321 };
322 try {
323 const result = await send("short msg", "https://discord.com/api/webhooks/test/token");
324 assertEquals(result.success, true);
325 assert(callCount >= 2, "Should have retried after 429");
335 globalThis.fetch = () => Promise.reject(new Error("network down"));
336 try {
337 const result = await send("msg", "https://discord.com/api/webhooks/test/token");
338 assertEquals(result.success, false);
339 } finally {
352 };
353 try {
354 const result = await send("hello world", "https://discord.com/api/webhooks/test/token");
355 assertEquals(result.success, true);
356 assert(bodies.length > 0);

catniplogger_test.ts27 matches

@catalloc•Updated 2 days ago
1import "../../test/_mocks/env.ts";
2import { assertEquals, assert } from "../../test/assert.ts";
3import { DiscordLogger, finalizeAllLoggers, createLogger } from "./logger.ts";
4
5// Helper: create a logger with no webhook (buffer-only, no network)
6function createBufferLogger(opts?: { minLevel?: "debug" | "info" | "warn" | "error"; maxBatchSize?: number }) {
7 return new DiscordLogger({
8 context: "Test",
9 webhookUrl: null,
58 console.log = (msg: string) => messages.push(msg);
59 try {
60 const logger = new DiscordLogger({
61 context: "ErrTest",
62 webhookUrl: null,
78 console.log = (msg: string) => messages.push(msg);
79 try {
80 const logger = new DiscordLogger({
81 context: "ErrTest",
82 webhookUrl: null,
95 console.log = (msg: string) => messages.push(msg);
96 try {
97 const logger = new DiscordLogger({
98 context: "ErrTest",
99 webhookUrl: null,
118 };
119 try {
120 const logger = new DiscordLogger({
121 context: "SendTest",
122 webhookUrl: "https://discord.com/api/webhooks/test/token",
123 fallbackToConsole: false,
124 batchIntervalMs: 100_000, // prevent auto-flush
140 };
141 try {
142 const logger = new DiscordLogger({
143 context: "FailTest",
144 webhookUrl: "https://discord.com/api/webhooks/test/token",
145 fallbackToConsole: false,
146 });
160 globalThis.fetch = () => Promise.reject(new Error("always fails"));
161 try {
162 const logger = new DiscordLogger({
163 context: "CapTest",
164 webhookUrl: "https://discord.com/api/webhooks/test/token",
165 fallbackToConsole: false,
166 maxBatchSize: 200,
198
199Deno.test("sanitize: redacts webhook URLs", () => {
200 const input = "Sending to https://discord.com/api/webhooks/123456789/ABCdef-token_123";
201 const result = sanitize(input);
202 assert(result.includes("[WEBHOOK_URL_REDACTED]"));
219 };
220 try {
221 const logger = new DiscordLogger({
222 context: "ErrorFlush",
223 webhookUrl: "https://discord.com/api/webhooks/test/token",
224 fallbackToConsole: false,
225 batchIntervalMs: 100_000, // very long to prevent timed flush
245 };
246 try {
247 const logger = new DiscordLogger({
248 context: "BatchFlush",
249 webhookUrl: "https://discord.com/api/webhooks/test/token",
250 fallbackToConsole: false,
251 maxBatchSize: 3,
274 };
275 try {
276 const logger = new DiscordLogger({
277 context: "DupFlush",
278 webhookUrl: "https://discord.com/api/webhooks/test/token",
279 fallbackToConsole: false,
280 batchIntervalMs: 100_000,
303 try {
304 const logger = createLogger("GlobalTest", {
305 webhookUrl: "https://discord.com/api/webhooks/test/token",
306 fallbackToConsole: false,
307 batchIntervalMs: 100_000,
332 };
333 try {
334 const logger = new DiscordLogger({
335 context: "TimerTest",
336 webhookUrl: "https://discord.com/api/webhooks/test/token",
337 fallbackToConsole: false,
338 batchIntervalMs: 50, // very short interval
358 };
359 try {
360 const logger = new DiscordLogger({
361 context: "FinalizeTest",
362 webhookUrl: "https://discord.com/api/webhooks/test/token",
363 fallbackToConsole: false,
364 batchIntervalMs: 999_999, // very long — should never fire naturally
382 globalThis.fetch = () => Promise.reject(new Error("send failed"));
383 try {
384 const logger = new DiscordLogger({
385 context: "NoDump",
386 webhookUrl: "https://discord.com/api/webhooks/test/token",
387 fallbackToConsole: false,
388 });
407 };
408 try {
409 const logger = new DiscordLogger({
410 context: "EmojiTest",
411 webhookUrl: "https://discord.com/api/webhooks/test/token",
412 fallbackToConsole: false,
413 batchIntervalMs: 999_999,

catniproutes_test.ts3 matches

@catalloc•Updated 2 days ago
51});
52
53Deno.test("handleLinkedRolesRedirect Location header points to discord.com/oauth2/authorize", async () => {
54 setVerifier(testVerifier);
55 const req = new Request("https://example.com/linked-roles");
56 const res = await handleLinkedRolesRedirect(req);
57 const location = res.headers.get("Location")!;
58 assert(location.startsWith("https://discord.com/oauth2/authorize?"));
59});
60
83 const location = res.headers.get("Location")!;
84 const params = new URLSearchParams(location.split("?")[1]);
85 // Test env sets DISCORD_APP_ID to "11111111111111111"
86 assertEquals(params.get("client_id"), "11111111111111111");
87});

catniphandler_test.ts1 match

@catalloc•Updated 2 days ago
215import "../../test/_mocks/sqlite.ts";
216import { mockFetch, restoreFetch, getCalls } from "../../test/_mocks/fetch.ts";
217import { kv } from "../../discord/persistence/kv.ts";
218import { sqlite } from "https://esm.town/v/std/sqlite/main.ts";
219

catnip359 file matches

@catalloc•Updated 2 days ago
Open source Discord bot template built for Val Town

vt-discord-bot

@catalloc•Updated 1 week ago
aibotcommander
Open-Hat-Lab is a creator and developer ecosystem for exploration, ideation and productivity. 🪄✨🎩 Discord: OpenSourceLab https://buymeacoffee.com/OpenHatLab
contdediscordc